我喜歡阿加瓦爾的一些修改答案,因爲它是可重複使用:
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