如何在不使用支持库的情况下为图像视图设置固定比例?

问题描述:

我希望我的ImageView拥有16:9的比例和android:layout_width="match_parent"如何在不使用支持库的情况下为图像视图设置固定比例?

我找不到如何在XML文件中设置它。我知道有一个PercentRelativeLayout可以帮助。但它支持API 23,我不想使用它。

我知道我可以通过编程设置比率。但它不好。因为当屏幕旋转时,我必须再次设置ImageView的大小。

有没有办法用XML文件做到这一点?

创建百​​分比ImageView需要覆盖ImageView中的onMeasure方法。

import android.content.Context; 
    import android.support.annotation.Nullable; 
    import android.util.AttributeSet; 
    import android.widget.ImageView; 
    public class PercentageImageView extends ImageView { 
     public PercentageImageView(Context context) { 
      super(context); 
     } 

     public PercentageImageView(Context context, @Nullable AttributeSet attrs) { 
      super(context, attrs); 
     } 

     public PercentageImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 
      super(context, attrs, defStyleAttr); 
     } 

     public PercentageImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
      super(context, attrs, defStyleAttr, defStyleRes); 
     super(context, attrs, defStyleAttr); 
     TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PercentageImageView, 0, 0); 
     try { 
      heightRatio = a.getFloat(R.styleable.PercentageImageView_imageHeightRatio, 0f); 
     } finally { 
      a.recycle(); 
     } 
     } 


     @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     int widthMode = MeasureSpec.getMode(widthMeasureSpec); 
     int heightMode = MeasureSpec.getMode(heightMeasureSpec); 
     if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) { 
      int width = MeasureSpec.getSize(widthMeasureSpec); 
      int height = MeasureSpec.getSize(heightMeasureSpec); 
      if (heightRatio != 0) { 
       height = (int) (heightRatio * width); 
      } 
      setMeasuredDimension(width, height); 
     } else { 
      super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
     } 
    } 
    } 

内值/ attrs.xml从XML

<resources> 

     <declare-styleable name="PercentageImageView"> 
      <attr name="imageHeightRatio" format="float" /> 
     </declare-styleable> 
    </resources> 

发送比像下面

<PercentageImageView 
      android:id="@+id/itemImage" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:scaleType="fitCenter" 
      app:imageHeightRatio="0.569" />// This is for 16:9 ratio. 
+0

不幸的是,这并不与约束布局和0dp(匹配约束)的工作,而不是match_parent,任何想法约束布局中要做什么? –