你可以用这个来实现这一点,创建扩展 imageView 的新 AspectRatioImageView:
public class AspectRatioImageView extends ImageView {
public AspectRatioImageView(Context context) {
super(context);
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drw = getDrawable();
if (null == drw || drw.getIntrinsicWidth() <= 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} else {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * drw.getIntrinsicHeight() / drw.getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}
}
然后在您的布局 xml 中使用:
<my.app.AspectRatioImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/ar_imageview"/>