2012-04-14 46 views
1

我試圖讓ImageView具有特定的寬度(比方說100dips),但要縮放以使高度爲維持比例的任何值,因此如果4 :3然後75蘸,如果4:5然後120蘸等Android - 縮放ImageView,使其始終在寬度上下陷

我已經嘗試了幾件事,但沒有任何工作。這是我目前的嘗試:

<ImageView 
     android:id="@+id/image" 
     android:layout_height="wrap_content" 
     android:layout_width="100dip" 
     android:adjustViewBounds="true" 
     android:src="@drawable/stub" 
     android:scaleType="fitCenter" /> 

高度的wrap_content沒有改善的東西,它只是使整個圖像更小(但保持縱橫比)。我怎樣才能完成我想要做的事情?

+0

正確的答案就在這裏:HTTP:// stackoverflow.com/questions/4677269/how-to-stretch-three-images-across-the-screen-preserving-aspect-ratio/4688335#4688335。我反覆搜查,但只是在我發佈時才發現它! :) – ajacian81 2012-04-14 12:51:23

回答

2

的follwing類添加到您的項目,改變你的佈局像這樣

查看

<my.package.name.AspectRatioImageView 
    android:layout_centerHorizontal="true" 
    android:src="@drawable/my_image" 
    android:id="@+id/my_image" 
    android:layout_height="wrap_content" 
    android:layout_width="100dp" 
    android:adjustViewBounds="true" /> 

package my.package.name; 

import android.content.Context; 
import android.util.AttributeSet; 
import android.widget.ImageView; 

/** 
* ImageView which scales an image while maintaining 
* the original image aspect ratio 
* 
*/ 
public class AspectRatioImageView extends ImageView { 

    /** 
    * Constructor 
    * 
    * @param Context context 
    */ 
    public AspectRatioImageView(Context context) { 

     super(context); 
    } 

    /** 
    * Constructor 
    * 
    * @param Context context 
    * @param AttributeSet attrs 
    */ 
    public AspectRatioImageView(Context context, AttributeSet attrs) { 

     super(context, attrs); 
    } 

    /** 
    * Constructor 
    * 
    * @param Context context 
    * @param AttributeSet attrs 
    * @param int defStyle 
    */ 
    public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) { 

     super(context, attrs, defStyle); 
    } 

    /** 
    * Called from the view renderer. 
    * Scales the image according to its aspect ratio. 
    */ 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 

     int width = MeasureSpec.getSize(widthMeasureSpec); 
     int height = width * getDrawable().getIntrinsicHeight()/getDrawable().getIntrinsicWidth(); 
     setMeasuredDimension(width, height); 
    } 
}