我喜欢阿加瓦尔的一些修改答案,因为它是可重复使用:
package com.yourpackage.widgets;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class AspectRatioImageView extends ImageView {
public AspectRatioImageView(Context context)
{
super(context);
this.setScaleType(ScaleType.FIT_XY);
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setScaleType(ScaleType.FIT_XY);
}
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setScaleType(ScaleType.FIT_XY);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
Drawable d = getDrawable();
if (d != null && d.getIntrinsicWidth() > 0)
{
int width = MeasureSpec.getSize(widthMeasureSpec);
if (width <= 0)
width = getLayoutParams().width;
int height = width * d.getIntrinsicHeight()/d.getIntrinsicWidth();
setMeasuredDimension(width, height);
}
else
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
现在在XML使用它:
<com.yourpackage.widgets.AspectRatioImageView
android:src="@drawable/yourdrawable"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
+1,美观大方,操作简单,只有我会保护它对'getIntrinsicWidth'为0(它会崩溃尝试除以它) –
adjustViewBounds也应该在AspectRatioImageView中完成http://developer.android.com/reference/android/widget/ImageView.html#setAdjustViewBounds%28boolean%29 – Nepster