Matrix: Matrix using ImageView set width and height, so that images can be displayed properly

 Load ImageView in Android ImageView generally do not give the width and height set an exact value, usually written directly:

<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#1B1B1B"
        android:src="@mipmap/ic_flight_log_share_pic_title" />

Or the width is set to match_parent, combined with scaleType property ImageView to ensure ImageView to display properly, because if the value is written dead, on different devices pictures may be deformed and distorted, sometimes set up scaleType also better, if the do not set scaleType, final estimates show into what even their own are not clear. But scaleType set to perfect it? Not really, to be displayed such as picture looks like this:

Use scaleType really can not guarantee picture distortion,

SetScaleType(ImageView.ScaleType.CENTER);

Or: SetScaleType (ImageView.ScaleType.CENTER_CROP);

Another example: setScaleType (ImageView.ScaleType.FIT_XY);

以上的三种scaleType应该是实际使用时应用的比较广泛的三种scaleType了,还有一些ScaleType.FIT_START,FIT_CENTER,FIT_END就不说了,但是就算设置了scaleType,充其量也就是能保证图片不变形,但是该有的问题还是会有,比如上面的几种scaleType,有的图片上下两侧会有留白,有的根本就显示不全,这里说明一下,ImageView默认的scaleType是FIT_CENTER,有留白是因为比如图片的宽大于高,在把图片放入到ImageView中时,会对图片进行等比例缩放,这样空出的部分自然就是留白了,一般在竖屏的情况下,通常图片的宽度会大于高度,这样在以FIT_CENTER显示的时候,上下都会有留白,但图片内容是可以全部显示的,那有没有什么办法既能全部显示图片内容,又可以使上下没有留白呢?

我的想法是,只要让ImageView的高度与ImageView里显示的图片高度一致就可以了,具体说来就是:

     iv_share_img.setImageBitmap(shareBitmap);
        iv_share_img.post(new Runnable() {
            @Override
            public void run() {
                /*
                 * 获取ImageView中image的宽高
                 * 注意:这里的宽高是Image原始的宽高,不是当前在ImageView中显示的宽高
                 */
                int img_width = iv_share_img.getDrawable().getBounds().width();
                int img_height = iv_share_img.getDrawable().getBounds().height();

                // 获取ImageView中Image的变换矩阵
                float[] emptyMatrix = new float[9];
                iv_share_img.getImageMatrix().getValues(emptyMatrix);

                // 分别从矩阵中获取X和Y的缩放系数
                float scaleX = emptyMatrix[0];
                float scaleY = emptyMatrix[4];

                // 计算Image在屏幕上实际绘制的宽高
                int realWidth = (int) (img_width * scaleX);
                int realHeight = (int) (img_height * scaleY);

                // 将ImageView的高度重新设置为ImageView中实际绘制的Image的高度,这样上下的留白就没有了,图片也可以完整显示了,不必
                // 刻意设置scaleType,使用默认的FIT_CENTER就好。
                ViewGroup.LayoutParams layoutParams = iv_share_img.getLayoutParams();
                layoutParams.height = realHeight;
                iv_share_img.setLayoutParams(layoutParams);
            }
        });

 

Guess you like

Origin www.cnblogs.com/yongdaimi/p/11130401.html