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

时间:2017-06-28 05:52:42

标签: android layout imageview

我希望我的ImageView有16:9的比例和android:layout_width="match_parent"

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

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

有没有办法用XML文件?

1 个答案:

答案 0 :(得分:2)

创建百分比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

    <resources>

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

如下所示从XML发送比率

<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.