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


这个控件实现起来很简单,来源是我的项目经理辉哥 他的博客地址   地址    交流群 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();
	}

	@Override
	protected 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值