按照指定比例展示宽高的自定义控件实现

1.json

2.按照指定比例展示宽高的自定义控件实现
为了让图片按照完美比例进行展现, 不被压缩, 需要自定义控件,该控件可以根据预设的比例来确定宽高
* 按照比例展示宽高的自定义控件
*
* @author Kevin
*
*/
public class RatioLayout extends FrameLayout {
private float ratio;
public RatioLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public RatioLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// 加载自定义属性的值
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.RatioLayout);
// 根据属性id获取属性值, 方式: R.styleable.名称_属性
ratio = typedArray.getFloat(R.styleable.RatioLayout_ratio, 0);
// 回收TypedArray, 释放内存
typedArray.recycle();
}
public RatioLayout(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// MeasureSpec.EXACTLY 确定值, 比如把宽高值写死,或者match_parent
// MeasureSpec.AT_MOST 至多, 能撑多大就多大, 类似wrap_content
// MeasureSpec.UNSPECIFIED 未指定大小
if (widthMode == MeasureSpec.EXACTLY
&& heightMode != MeasureSpec.EXACTLY && ratio != 0) {
// 1. 根据布局宽度推算图片宽度
int imageWidth = widthSize - getPaddingLeft() - getPaddingRight();
// 2. 根据图片宽度和宽高比,推算图片高度
int imageHeight = (int) (imageWidth / ratio);
// 3. 根据图片高度, 推算布局高度
heightSize = imageHeight + getPaddingTop() + getPaddingBottom();
// 4. 根据布局高度, 推算heightMeasureSpec
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,
MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
自定义属性
values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RatioLayout">
<attr name="ratio" format="float" />
</declare-styleable>
</resources>
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:itheima="http://schemas.android.com/apk/res/com.itheima.googleplay74"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="@drawable/list_item_bg_selector"
android:orientation="vertical" >
<com.itheima.googleplay74.ui.view.RatioLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
itheima:ratio="2.43" >
<ImageView
android:id="@+id/iv_pic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/subject_default" />
</com.itheima.googleplay74.ui.view.RatioLayout>
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="标题"
android:textColor="#000"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
浙公网安备 33010602011771号