Android:无法在屏幕中央放置矩阵图像视图?

时间:2015-04-17 05:25:14

标签: android android-layout imageview android-imageview android-framelayout

我正致力于Image Zooming。一切都很好。我试图在布局的中心显示矩阵图像。但我无法做到。

我的xml是:

<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>

我已经从堆栈溢出中使用了这个解决方案,但我没有得到中心放置的图像。图像正对齐屏幕的左上角。请帮帮我。

@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();
}

1 个答案:

答案 0 :(得分:2)

我在这里使用drawable(设置为imageview)固有宽度和高度作为screenWidth和screenHeight

这是我的解决方案:

@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();

}