본문 바로가기

Programming/Android

[Android] Square ImageView (정사각형 ImageView)

  • Square ImageView(Custom)

프로필 사진이나 기타 사진등을 정사각형으로 보여주기 위해 만들게 됨(특히 LinearLayout에서 비율로 보여줄때)

 

    1. Source Code

→ 기준(mFit)을 입력 받아 onMeasure함수에서 기준에 따라 크기를 정함.

 

1) SquareImageView.java

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;


public class SquareImageView extends android.support.v7.widget.AppCompatImageView {

private String mFit = "normal";

public SquareImageView(Context context) {
super(context);
}

public SquareImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}

public SquareImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}

private void init(Context context, @Nullable AttributeSet attrs) {
mFit = context.obtainStyledAttributes(attrs, R.styleable.SquareImageView).getString(R.styleable.SquareImageView_fit);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(TextUtils.equals(mFit, "width")) { // fit width
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
} else if(TextUtils.equals(mFit, "height")) { // fit height
super.onMeasure(heightMeasureSpec, heightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}

2) attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SquareImageView">
<attr name="fit" format="string" />
</declare-styleable>
</resources>

 

2. 예제 xml

 

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.phg.practice.MainActivity">

<com.example.phg.practice.SquareImageView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/background_dark"
android:src="@mipmap/ic_launcher"
app:fit="width" />

<com.example.phg.practice.SquareImageView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_blue_bright"
android:src="@mipmap/ic_launcher"
app:fit="width" />

<com.example.phg.practice.SquareImageView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_orange_dark"
android:src="@mipmap/ic_launcher"
app:fit="width" />
</LinearLayout>