2012-06-19 11 views
2

我在應用程序中設置了以下矩形圖像。Android:如何擴展具有相同比例的矩形圖像以適應屏幕

enter image description here

現在我想擴大與相同比例的圖像兩側,直到它適合於screen.But我不能得到預期的圖像。

enter image description here

到目前爲止,我的代碼是:

<ImageView 
    android:id="@+id/imgid" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:src="@drawable/shayneward" 
    android:scaleType="fitXY"/> 

它不關心,圖像被切斷,但直到它適合在屏幕應該兩邊用相同的比例擴大。

回答

6

android:scaleType="fitXY"更改爲android:scaleType="centerCrop"以獲得所需的行爲。

不同的縮放選項記錄在ImageView.ScaleType下。

+0

沒錯,+1它 –

+0

非常感謝。 'android:scaleType =「centerCrop」'完全適合我。 –

4

嘗試使用此:

android:scaleType="centerCrop" 

從Android文檔,中心作物執行以下操作:

縮放圖像均勻(保持圖像的縱橫比),使得 兩個尺寸(寬度和高度)將等於或大於視圖的相應尺寸(減去填充)的 。

查看文檔ImageView.ScaleTypehere

+0

在這裏你已經得到了正確的縮放類型,但錯誤的常量 - 在XML中它應該是「centerCrop」,而不是「CENTER_CROP」。 –

+0

謝謝,如果以編程方式設置,我不小心把你使用的常量。 – happydude

1

如果圖像太小可能會成爲一個問題,因爲它不適合屏幕尺寸。

我使用這個類來解決這個問題:

public class FixedCenterCrop extends ImageView { 


    public FixedCenterCrop(Context context) { 
     super(context); 
     setScaleType(ScaleType.MATRIX); 
    } 

    public FixedCenterCrop(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setScaleType(ScaleType.MATRIX); 
    } 

    public FixedCenterCrop(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     setScaleType(ScaleType.MATRIX); 
    } 


    @Override 
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
     super.onLayout(changed, left, top, right, bottom); 
     recomputeImgMatrix(); 
    } 

    @Override 
    protected boolean setFrame(int l, int t, int r, int b) { 
     recomputeImgMatrix(); 
     return super.setFrame(l, t, r, b); 
    } 

    private void recomputeImgMatrix() { 
     final Matrix matrix = getImageMatrix(); 

     float scale; 
     final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight(); 
     final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom(); 
     final int drawableWidth = getDrawable().getIntrinsicWidth(); 
     final int drawableHeight = getDrawable().getIntrinsicHeight(); 

     if (drawableWidth * viewHeight > drawableHeight * viewWidth) { 
      scale = (float) viewHeight/(float) drawableHeight; 
     } else { 
      scale = (float) viewWidth/(float) drawableWidth; 
     } 

     matrix.setScale(scale, scale); 
     matrix.postTranslate((viewWidth - drawableWidth * scale)/2, (viewHeight - drawableHeight*scale)/2); 
     setImageMatrix(matrix); 
    } 
} 
相關問題