sravanalakshmi.sunkara
sravanalakshmi.sunkara

Reputation: 1161

Android: Not able to place an matrix imageview at the center of the screen?

I am working on Image Zooming. Everything is fine.I am trying to display an matrix image at the center of the layout. But I am not able to do it.

My xml is:

<FrameLayout
    android:id="@+id/root1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/root"
    >

    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="matrix"
        android:src="@drawable/ic_launcher" >
    </ImageView>
</FrameLayout>

And I've used this solution from stack overflow but I am not getting center placed image. Image is aligning top left of the screen. Please help me.

@Override
public void onWindowFocusChanged(boolean hasFocus) {

    super.onWindowFocusChanged(hasFocus);

    screenWidth = rel.getWidth();
    screenHeight = rel.getHeight();

    Log.e("",
            "Image Width : " + image.getWidth() + "  >  "
                    + image.getHeight());
    Log.e("", "screen Width : " + screenWidth + "  >  " + screenHeight);
    Matrix matrix = image.getImageMatrix();
    RectF drawableRect = new RectF(0, 0, image.getWidth(),
            image.getHeight());
    RectF viewRect = new RectF(0, 0, screenWidth, screenHeight);
    matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
    image.setImageMatrix(matrix);
    image.invalidate();
}

Upvotes: 1

Views: 1112

Answers (1)

sravanalakshmi.sunkara
sravanalakshmi.sunkara

Reputation: 1161

Here I've to use drawable(which is set to imageview) intrinsic width and height as a screenWidth and screenHeight

Here is my solution:

@Override
public void onWindowFocusChanged(boolean hasFocus) {

    super.onWindowFocusChanged(hasFocus);

    float imageWidth = imageView.getDrawable().getIntrinsicWidth();
    float imageHeight = imageView.getDrawable().getIntrinsicHeight();
    RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight);
    RectF viewRect = new RectF(0, 0, imageView.getWidth(),
            imageView.getHeight());
    Matrix matrix = imageView.getMatrix();
    matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
    imageView.setImageMatrix(matrix);
    imageView.invalidate();

}

Upvotes: 2

Related Questions