How to align ImageView to the bottom, fill its width and height, and keep its aspect ratio?

后端 未结 6 1960
攒了一身酷
攒了一身酷 2021-02-05 11:36

Background

There are various XML attributes for ImageView to scale its content , and various layout views that allow to place views and set their sizes.

Howeve

6条回答
  •  心在旅途
    2021-02-05 12:37

    You can use is custom FitWidthAtBottomImageView to achieve this code:

    public class FitWidthAtBottomImageView extends ImageView {
        public FitWidthAtBottomImageView(Context context) {
            super(context);
        }
    
        public FitWidthAtBottomImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public FitWidthAtBottomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public FitWidthAtBottomImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            int i = getWidth() - getPaddingLeft() - getPaddingRight();
            int j = getHeight() - getPaddingTop() - getPaddingBottom();
            if (getBackground() != null) {
                getBackground().draw(canvas);
            }
            if (getDrawable() != null && getDrawable() instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
                int h = bitmap.getHeight() * i / bitmap.getWidth();
                canvas.drawBitmap(bitmap, null, new RectF(getPaddingLeft(), getPaddingTop() + j - h, getPaddingLeft() + i, getHeight() - getPaddingBottom()), null);
            } else {
                super.onDraw(canvas);
            }
    
        }
    }
    

    by manually draw the bottom aligned image that you want.

提交回复
热议问题