wxr
2022-11-24 2af932533ef851bf983385244e9912976dbd4daa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
 * All rights Reserved.
 * 16:9宽高比的ImageView
 */
package com.mm.android.deviceaddmodule.mobilecommon.widget;
 
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
 
import com.mm.android.deviceaddmodule.R;
 
/**
 * 自定义宽高比的ImageView,默认1:1
 
 * 自定义属性:
 *  <declare-styleable name="CommonRatioImageView">
 <attr name="width_relative" format="dimension" /> 相对宽度
 <attr name="height_relative" format="dimension" />相对高度
 </declare-styleable>
 *
 * 应用:
 * <CommonRatioImageView
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:width_relative="16dp"
     app:height_relative="9dp"
    />
 *
 */
public class CommonRatioImageView extends android.support.v7.widget.AppCompatImageView {
 
    private float width_relative = 1.0f;
    private float height_relative = 1.0f;
 
    public CommonRatioImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CommonRatioImageView);
        if(array == null)return;
        width_relative = array.getDimension(R.styleable.CommonRatioImageView_width_relative,1.0f);
        height_relative = array.getDimension(R.styleable.CommonRatioImageView_height_relative,1.0f);
        array.recycle();
    }
 
    public CommonRatioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CommonRatioImageView);
        if(array == null)return;
        width_relative = array.getDimension(R.styleable.CommonRatioImageView_width_relative,1.0f);
        height_relative = array.getDimension(R.styleable.CommonRatioImageView_height_relative,1.0f);
        array.recycle();
    }
 
    public CommonRatioImageView(Context context) {
        super(context);
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
        int heightSize = Math.round(widthSize * height_relative/width_relative);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}