自定义View之ImageView做屏幕适配

由于近期的项目图片非常的多,而且适配就遇到了一定的难度,所以自定义ImageView来做适配是比较成功的解决办法。
1.UI提供的图片的比例是16:9(当然不是非常专业,小公司)
2.所以就通过获取手机的屏幕宽度,来设置宽高比为16:9
下面上代码:

“`
package com.example.li.ueui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RatioImageView extends ImageView{

public  float ratio;//width/height
public RatioImageView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public RatioImageView(Context context) {
    this(context, null);
}

public RatioImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    ratio=attrs.getAttributeFloatValue("http://schemas.android.com/apk/res/com.example.li.ueui", "riv_ratio", 0);

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    if(ratio!=0){
        int height = (int) (width/ratio);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

}

“`(1)http://schemas.android.com/apk/res/com.example.li.ueui这个参数是命名空间在布局中会用的到
(2)获取宽度,然后计算出高度,当然是通过16:9,通过自定义属性传进来的

attrs文件中定义的 format代表的是属性的类型,float类型

<declare-styleable name="RatioImageView">
        <attr name="riv_ratio" format="float"></attr>
    </declare-styleable>
 (3)在布局中应用,用到了命名空间,还有自定义属性,ratio,四舍五入,riv_ratio 1.78
 宽度是match_parent,对应的测量规则是MeasureSpec.EXACTLY,也就是有确定的值不用测量,直接给具体的宽度,heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);通过这行代码给高度的测量规则设置成也是具体的宽度,这样就图片就算拉伸也是等比例的,所以影响不大。

“`

“`(4)在代码中运用就不写了,相信大家都会的,可以用UIL,glide,Picasso等网络框架区加载网络图片。
如果有不正确的地方,欢迎大家指正,谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值