android中自定義ImageView的高度自適應

有的時候會遇到使用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);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章