自定义按比例显示的ImageView
1,实现效果
-
按比例显示的ImageView
2,实现逻辑
【1】去看服务端给你的图片比例是多少,
-
宽度/高度 计算宽高比。
-
高:宽 = 1:2.43
【1】创建构造方法
public class RatioImageView extends ImageView {}
【2】布局中使用
<com.heima.googlemarket.ui.view.RatioImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
【3】创建自定义属性
-
Values 创attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RatioImageView">
<attr name="ratio" format="float"/>
</declare-styleable>
</resources>
-
控件布局中使用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:padding = "5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.xiaoshuai.googlemarket.ui.view.RatioImageView
android:id="@+id/iv_image"
app:ratio="2.43"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
//参数1命名空间,参数2自定义属性的属性名,参数3默认值
ratio = attrs.getAttributeFloatValue(NAMESPACE, "ratio", 0.0f);
-
在onMeasure获取宽度,他一定是一个具体的值,match_parent+5dp是父布局的match_parent,父布局的match_parent
-
宽度除除以比例等到高度的精确值
int heightSize = (int)(widthSize/ratio+0.5f);
-
生成具体的32位数高度值进行测量
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,MeasureSpec.EXACTLY);
【3】全部代码
/**
* Created by HASEE on 2019/4/6.
* 让此控件的宽高和服务器端返回图片的宽高比例一致
* 高:宽 = 1:2.43
*/
public class RatioImageView extends ImageView {
private static final String TAG = "RatioImageView";
public static String NAMESPACE = "http://schemas.android.com/apk/res-auto";
//从自定义属性中获取到的属性值
private final float ratio;
public RatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
ratio = attrs.getAttributeFloatValue(NAMESPACE, "ratio", 0.0f);
Log.i(TAG,"======================ratio = "+ratio);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//widthMeasureSpec 32位2机制数字 2位 30位
//00 01 10 11 4种
//30位 指定宽度大小
//MeasureSpec.AT_MOST 至多
//MeasureSpec.EXACTLY 精确值
//MeasureSpec.UNSPECIFIED ListView
//1.获取自定义控件的宽度具体值
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
//2.获取高度值精确值
int heightSize = (int)(widthSize/ratio+0.5f);
//3.用精确模式搭配精确值,生成高度的32位数
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}