按照比例显示的 RelativeLayout

dim.red

需求:

要求移动端图片宽高1:1显示.并且图片宽度要充满手机屏幕的宽度.
这个要怎么做?
ImageView.scaleType 的作用
研究了一下 ImageView 的 scaleType 属性和常用布局.
发现貌似单单在只靠 xml 布局中不能解决的样子.

怎么办?

方法1:
是在代码中手动的设置高度给 ImageView.
这样是一种方法.但是方法会不会太 low, 拉长了 Actitvity 的代码量?
方法2:
继承RelativeLayout控件,复写 onMeasure() 方法.

onMeasure()方法:

       @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        if(mScale != -1){
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec((int) (MeasureSpec.getSize(widthMeasureSpec) * mScale), MeasureSpec.getMode(widthMeasureSpec)));

        }else{
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

   }

其中mScale 代表 height/width的值.

sample#

   <com.mingle.widget.ScaleLayout
        android:layout_width="fill_parent"
        app:scale="0.75"
        android:layout_height="wrap_content">

    <ImageView
        android:layout_width="fill_parent"
        android:src="@mipmap/bg"
        android:scaleType="fitXY"
        android:layout_height="fill_parent" />
    </com.mingle.widget.ScaleLayout>

ScaleLayout 包裹ImageView,用 app:scale 设置宽高比:
android:layout_width="fill_parent"
android:layout_height="fill_parent" 设置ImageView,并且scaleType设置为fitXY.

github

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容