Android ImageView adjusting parent's height and fitting width

前端 未结 5 525
终归单人心
终归单人心 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:38

    I made a slight change to @Seraphim S's solution to account for cases where the image may be wide, and the view's bounds also wide (for example, rotating the device to landscape mode).

    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) {
    
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = MeasureSpec.getSize(heightMeasureSpec);
    
                if (width >= height) {
                    width = (int) Math.ceil((float) height * (float) d.getIntrinsicWidth() / (float) d.getIntrinsicHeight());
                } else {
                    height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
                }
    
                setMeasuredDimension(width, height);
            } else {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        }
    }
    

提交回复
热议问题