2012-04-14 45 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); 
    } 
}