指定宽度的正方形ImageView:
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);
}
...
}
指定高度的正方形ImageView:
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);
}
...
}
一个最小尺寸为正方形的ImageView:
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);
}
...
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMeasuredWidth(); int height = getMeasuredHeight(); // 优化,除非需要,否则不进行两次测量 if (width != height) { setMeasuredDimension(width, width); } }
- Chantell Osejo