Android ImageView adjusting parent's height and fitting width

前端 未结 5 517
终归单人心
终归单人心 2020-11-28 02:06

Update : I solved this issue by using the method described in this answer

I\'m a bit stuck with this issue, which I think should be pretty simple.

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 02:22

    Thanks to @Julien and @js. Here is complete solution of ImageView that will stretch bitmap height preserving aspect ratio even if bitmap is smaller than ImageView.

    public class ResizableImageView extends ImageView {
    
        public ResizableImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override 
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
             Drawable d = getDrawable();
    
             if(d!=null){
                     // ceil not round - avoid thin vertical gaps along the left/right edges
                     int width = MeasureSpec.getSize(widthMeasureSpec);
                     int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
                     setMeasuredDimension(width, height);
             }else{
                     super.onMeasure(widthMeasureSpec, heightMeasureSpec);
             }
        }
    
    }
    

    You can use this class in your xml layouts instead ImageView.

    
    

提交回复
热议问题