Android center Bitmap in ImageView matrix

落花浮王杯 提交于 2019-12-04 18:56:50

If you want to align bitmap to center then you ImageView layout should be:

<ImageView
    android:id="@+id/top_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="center"/>

EDIT:

In case if you need scaleType "matrix" then use next solution:

<ImageView
    android:id="@+id/top_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="matrix"
    />

And then in code change offset of image:

    final ImageView imageView = (ImageView) findViewById(R.id.top_image);

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT >= 16) {
                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }

            Drawable drawable = imageView.getDrawable();
            Rect rectDrawable = drawable.getBounds();
            float leftOffset = (imageView.getMeasuredWidth() - rectDrawable.width()) / 2f;
            float topOffset = (imageView.getMeasuredHeight() - rectDrawable.height()) / 2f;

            Matrix matrix = imageView.getImageMatrix();
            matrix.postTranslate(leftOffset, topOffset);
            imageView.setImageMatrix(matrix);
            imageView.invalidate();
        }
    });

This worked for me.

<ImageView
    android:id="@+id/top_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="matrix"
    />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!