自定義控件之圖片適配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>


發佈了490 篇原創文章 · 獲贊 24 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章