有的时候会遇到使用ImageView的图片会拉伸,这里记录一下自定义ImageView的高度自适应。
public class AutoScaleHeightImageView extends ImageView {
public AutoScaleHeightImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if(drawable != null){
int width = drawable.getMinimumWidth();
int height = drawable.getMinimumHeight();
float scale = (float)height/width;
int widthMeasure = MeasureSpec.getSize(widthMeasureSpec);
int heightMeasure = (int)(widthMeasure*scale);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightMeasure, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}