自定义图片比例适配控件 ProportionImageView

来源:互联网 发布:sql server报价 编辑:程序博客网 时间:2024/05/17 01:43


这个控件实现起来很简单,来源是我的项目经理辉哥 他的博客地址   地址    交流群 546270670  欢迎大家 


直接上代码

/** *  * ============================================================ *  * project name : TiantianFangFu *  * copyright ZENG HUI (c) 2015 *  * author : HUI *  * version : 1.0 *  * date created : On June, 2015 *  * description : 自己设置view宽高比(一般会知道宽), 不需要去适配了 *  * revision history : *  * ============================================================ *  */public class ProportionImageView extends ImageView {// 用float可能更好private float mWidthPro;private float mHeightPro;public ProportionImageView(Context context) {this(context, null);}public ProportionImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public ProportionImageView(Context context, AttributeSet attrs,   int defStyleAttr) {super(context, attrs, defStyleAttr);initAttribute(context, attrs);}private void initAttribute(Context context, AttributeSet attrs) {TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.ProportionImageView);mWidthPro = array.getFloat(R.styleable.ProportionImageView_width_proportion, mWidthPro);mHeightPro = array.getFloat(R.styleable.ProportionImageView_height_proportion, mHeightPro);array.recycle();}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {// 先测量一下super.onMeasure(widthMeasureSpec, heightMeasureSpec);// 用户没有设置宽高比就不处理if (mWidthPro == 0 || mHeightPro == 0) {return;}// 拿到宽int width = getMeasuredWidth();int height = (int) (width * (mHeightPro / mWidthPro));// 宽和高按比例设置setMeasuredDimension(width, height);}}


  <!-- 宽高比的图片 -->

    <declare-styleable name="ProportionImageView">

        <!-- 宽度比例 float -->

        <attr name="width_proportion" format="float" />

        <!-- 高度比例 float -->

        <attr name="height_proportion" format="float" />

    </declare-styleable>




使用



        <com.hc.baibianjiajia.ui.ProportionImageView            android:id="@+id/note_iv"            android:layout_width="match_parent"            android:layout_height="wrap_content"            hui:width_proportion="2"            hui:height_proportion="1"            android:scaleType="centerCrop"            android:layout_marginBottom="10dp" />

 hui:width_proportion="2"   宽 2 hui:height_proportion="1"   高 1



0 0
原创粉丝点击