自定义控件之图片适配RatioLayout

package com.study.googleplay.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.study.googleplay.R;

/**
 * 自定义控件,按比例来决定布局高度
 * 确保了图片不被拉伸,按照原比例显示
 * @author TCL
 * @date 2016-6-9
 */
public class RatioLayout extends FrameLayout {

	private float ratio;

	public RatioLayout(Context context) {
		super(context);
	}

	public RatioLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public RatioLayout(Context context, AttributeSet attrs) {
		super(context, attrs);

		// 获取属性值
		// attrs.getAttributeFloatValue("tcl", "ratio", 1);

		TypedArray typedArray = context.obtainStyledAttributes(attrs,
				R.styleable.RatioLayout);
		ratio = typedArray.getFloat(R.styleable.RatioLayout_ratio, -1);
		typedArray.recycle();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		// 1.获取宽度
		// 2.根据宽度和比例ratio,计算控件高度
		// 3.重新测量控件
		int width = MeasureSpec.getSize(widthMeasureSpec);// 获取宽度值
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);// 获取宽度模式

		int height = MeasureSpec.getSize(heightMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);

		// 宽度确定,高度不确定,ratio合法,才计算高度值
		if (widthMode == MeasureSpec.EXACTLY
				&& heightMode != MeasureSpec.EXACTLY && ratio > 0) {

			int imageWidth = width - getPaddingLeft() - getPaddingRight();// 图片真实宽度要减去内边距

			// 高度 = 宽度/比例
			int imageHeight = (int) (imageWidth / ratio);

			height = imageHeight + getPaddingBottom() + getPaddingTop();// 控件高度=图片高度+内边距

			// 根据最新的高度来重新生成(高度是确定模式)
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
					MeasureSpec.EXACTLY);
		}

		// MeasureSpec.AT_MOST;至多模式,控件有多大就显示多大 wrap_content
		// MeasureSpec.EXACTLY;确定模式模式,类似宽高写死 match_parent
		// MeasureSpec.UNSPECIFIED;未知模式

		// 根据最新的高度来测量控件(高度是确定模式)
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}

attrs:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="RatioLayout">
        <attr name="ratio" format="float" />
    </declare-styleable>

</resources>

使用:

<com.study.googleplay.view.RatioLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tcl:ratio="2.43" >

        <ImageView
            android:id="@+id/iv_pic"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@null"
            android:src="@drawable/subject_default" />
    </com.study.googleplay.view.RatioLayout>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值