2012-04-14 1 views
1

ImageViewを特定の幅(100dipsと言う)にしたいが、高さは比率を維持する任意の値であるようにスケーリングする:3、75ディップ、4:5、120ディップなど。Android - 画像の幅を常に100ディップに調整する

私はいくつかのことを試みましたが、何も機能していません。高さwrap_contentは、物事を改善しなかった、それだけで画像全体が小さく(しかし、アスペクト比を維持しました)

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

:これは私の現在の試みです。私は何をしようとしていますか?

+0

のようなあなたのレイアウトを変更します。http:// stackoverflow.com/questions/4677269/how-to-stretch-three-images-across-the-screen-preserving-aspect-ratio/4688335#4688335私は繰り返し検索しましたが、私が投稿していたときにそれを見つけました! :) – ajacian81

答えて

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); 
    } 
} 
関連する問題