ImageView保持前景src和ImageView的高度一致

来源:互联网 发布:汽车ecu编程器 编辑:程序博客网 时间:2024/05/17 02:58
public class RatioImageView extends ImageView {    public RatioImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        Drawable drawable = getDrawable();        if (drawable != null) {            // 因为高有问题,所以我们修改这高,让它按比例算出这个高            int picRealHeight = drawable.getMinimumHeight();    // 获取图片真实的高            int picRealWidth = drawable.getMinimumWidth();      // 获取图片真实的宽            float scale = (float) picRealHeight / picRealWidth; // 计算图片高和宽的比例            int width = MeasureSpec.getSize(widthMeasureSpec);  // 获取测量规格            int height = (int) (width * scale);                 // 按比例计算高度            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);   // 创建测量规格        }        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }}

了解ImageView的几个概念

① 前景src

src属性默认会保持图片比例不变。


② ImageView的高度

默认采用图片真实的高。


③ 对于ImageView来说

onMeasure用来测量前景src的宽高尺寸;

onLayout不起作用,其父亲为空实现;


④ 为何这么做就好了呢?

ImageView的高度设置为wrap_content,则ImageView的高度就是原始图片的高度,

而前景src要进行等比例的缩小,显示效果就是图片前景高度和ImagView高度不匹配,

将ImageView高度在onMeasure里设置为前景src高度,此时ImageView和前景src高度一致;


⑤ onMeasure作用是啥?

   设置ImageView的size和measureSpec:ImageView尺寸和测量规格;

    此时ImageView自身获取到其自身的信息,自身调用onDraw方法;

    onMeasure由其父容器的measure调用,为其传递尺寸信息;

    在ImageView的onMeasure方法里,ImageView可以决定自己的尺寸信息是否需要修改,

   如果不需要修改,就采取父容器传递过来的尺寸信息。


要求ImageView的前景src和ImageView的高度一致;

要求美工切图要统一比例,我们对图片高度不控制,完全由图片宽度和目标图片宽度的scale决定。


除了自定义ImageView手动设置ImagaView的高度之外,还可以利用ImageView自带的一个属性在xml中声明,自动设置ImageView的前景和ImagaView的高度自适应:


 <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:adjustViewBounds="true"        android:background="#6000"        android:src="@drawable/sp" />    <View        android:layout_width="match_parent"        android:layout_height="30dp" />    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#6000"        android:scaleType="fitStart"        android:src="@drawable/sp" />

第一张ImageView高度自适应

第二张前景和ImageView的宽度不匹配,之所以出现这种情况是因为,为了保证前景(图片)的宽高比例不变,对图片宽度和高度等比例缩放到的最大程度。






0 0
原创粉丝点击