Created
November 14, 2013 15:53
-
-
Save lesleh/7469169 to your computer and use it in GitHub Desktop.
Square ImageView implementation for Android.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<com.example.SquareImageView | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:src="@drawable/example" | |
android:scaleMode="centerCrop" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.util.AttributeSet; | |
import android.widget.ImageView; | |
public class SquareImageView extends ImageView { | |
// Inherited constructors | |
public SquareImageView(Context context) { | |
super(context); | |
} | |
public SquareImageView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public SquareImageView(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
} | |
@Override | |
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
int widthMode = MeasureSpec.getMode(widthMeasureSpec); | |
int heightMode = MeasureSpec.getMode(heightMeasureSpec); | |
int widthSize = MeasureSpec.getSize(widthMeasureSpec); | |
int heightSize = MeasureSpec.getSize(heightMeasureSpec); | |
// If one of the measures is match_parent, use that one to determine the size. | |
// If not, use the default implementation of onMeasure. | |
if(widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) { | |
setMeasuredDimension(widthSize, widthSize); | |
} else if(heightMode == MeasureSpec.EXACTLY && widthMode != MeasureSpec.EXACTLY) { | |
setMeasuredDimension(heightSize, heightSize); | |
} else { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment