指定宽度的 squareImageView:
public class SquareImageViewByWidth extends AppCompatImageView {
public SquareImageViewByWidth(Context context) {
super(context);
}
public SquareImageViewByWidth(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageViewByWidth(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width= getMeasuredWidth();
setMeasuredDimension(width, width);
}
...
}
指定高度的 squareImageView:
public class SquareImageViewByHeight extends AppCompatImageView {
public SquareImageViewByHeight(Context context) {
super(context);
}
public SquareImageViewByHeight(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageViewByHeight(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = getMeasuredHeight();
setMeasuredDimension(height, height);
}
...
}
最小尺寸的 squareImageView:
public class SquareImageViewByMin extends AppCompatImageView {
public SquareImageViewByHeight(Context context) {
super(context);
}
public SquareImageViewByHeight(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageViewByHeight(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int minSize = Math.min(width, height);
setMeasuredDimension(minSize, minSize);
}
...
}