Skip to content

Instantly share code, notes, and snippets.

@emanonwzy
Created January 10, 2015 08:36
Show Gist options
  • Save emanonwzy/25c0f65bde56abcfa301 to your computer and use it in GitHub Desktop.
Save emanonwzy/25c0f65bde56abcfa301 to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by zeyiwu on 1/5/15.
*/
public class SquareImageView extends ImageView {
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);
if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width;
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment