1

ImageViewに特定の幅(たとえば100ディップ)を持たせようとしていますが、高さが比率を維持する値になるようにスケーリングします。つまり、4:3の場合は75ディップ、4:5の場合は120ディップなどです。 。

私はいくつかのことを試しましたが、何も機能していません。これは私の現在の試みです:

<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は状況を改善せず、画像全体を小さくしただけです(ただし、アスペクト比は維持しました)。どうすれば自分がやろうとしていることを達成できますか?

4

1 に答える 1

2

次のクラスをプロジェクトに追加し、このようにレイアウトを変更します

意見

<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);
    }
}
于 2012-04-14T16:48:35.157 に答える