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

后端 未结 6 2045
攒了一身酷
攒了一身酷 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:32

    this is a proof-om-concept custom ImageView, you will need to add missing constructors and perform the Matrix setting whenever ImageView's Drawable changes:

    class V extends ImageView {
        public V(Context context) {
            super(context);
            setScaleType(ScaleType.MATRIX);
        }
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            Drawable d = getDrawable();
            if (d != null) {
                Matrix matrix = new Matrix();
                RectF src = new RectF(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                RectF dst = new RectF(0, 0, w, h);
                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
                float[] points = {
                        0, d.getIntrinsicHeight()
                };
                matrix.mapPoints(points);
                matrix.postTranslate(0, h - points[1]);
                setImageMatrix(matrix);
            }
        }
    }
    

    how it works in short:

    • first the Matrix is set by calling Matrix.setRectToRect() with stf == Matrix.ScaleToFit.CENTER, the result is the same as ImageView.ScaleType.FIT_CENTER

    • then in order to align the Drawable to the bottom Matrix.mapPoints() is called, it maps the Drawable's left/bottom corner and the result is transformed point as would be seen in the ImageView

    • and finally Matrix.postTranslate() translates the MAtrix in Y axis to the ImageView's bottom

提交回复
热议问题