解决 ImageView 属性 adjustViewBounds 无效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ScalingImageView extends ImageView {

  public ScalingImageView(Context context) {
    super(context);
  }
  
  public ScalingImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  
  public ScalingImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }
  
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Drawable mDrawable = getDrawable();
    if (mDrawable != null) {
      int mDrawableWidth = mDrawable.getIntrinsicWidth();
      int mDrawableHeight = mDrawable.getIntrinsicHeight();
      float actualAspect = (float) mDrawableWidth / (float) mDrawableHeight;
     
      // Assuming the width is ok, so we calculate the height.
      final int actualWidth = MeasureSpec.getSize(widthMeasureSpec);
      final int height = (int) (actualWidth / actualAspect);
      heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }
}