1

我正在研究圖像縮放。一切都很好。我試圖在佈局的中心顯示矩陣圖像。但我無法做到。Android:無法將矩陣imageview放置在屏幕中央?

我的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(); 
} 
+0

任何原因,你不使用'RelativeLayout'? –

+0

我也使用了相對佈局,但沒有結果。@ XaverKapeller –

+1

問題不在於ImageView的位置,而在於它的大小。你已經將其高度和寬度設置爲'match_parent',這使得'ImageView'與包含它的佈局一樣大。改爲使用'wrap_content'。 –

回答

2

在這裏,我用繪製(被設置爲ImageView的)內部寬度和高度屏幕寬度和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(); 

}