标签:
有时候服务器返回的图片有可能宽高是不一样的,所以需要按照一定宽高比例去显示,修改专题界面
<resources><declare-styleable name="com.itheima.googleplay.view.RatioLayout"><attr name="ratio" format="float"></attr></declare-styleable></resources>
public class RatioLayout extends FrameLayout {// 按照宽高比例去显示private float ratio = 2.43f; // 比例值,不要去写死,这样只需要调下方法根据自己需要去修改public void setRatio(float ratio) {this.ratio = ratio;}public RatioLayout(Context context) {super(context);}public RatioLayout(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// 参数1 命名控件 参数2 属性的名字 参数3 默认的值float ratio = attrs.getAttributeFloatValue("http://schemas.android.com/apk/res/com.itheima.googleplay","ratio", 2.43f);setRatio(ratio);}public RatioLayout(Context context, AttributeSet attrs) {this(context, attrs, 0);}// 测量当前布局@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {// widthMeasureSpec 宽度的规则 包含了两部分 模式 值int widthMode = MeasureSpec.getMode(widthMeasureSpec); // 模式int widthSize = MeasureSpec.getSize(widthMeasureSpec);// 宽度大小int width = widthSize - getPaddingLeft() - getPaddingRight();// 去掉左右两边的paddingint heightMode = MeasureSpec.getMode(heightMeasureSpec); // 模式int heightSize = MeasureSpec.getSize(heightMeasureSpec);// 高度大小int height = heightSize - getPaddingTop() - getPaddingBottom();// 去掉上下两边的paddingif (widthMode == MeasureSpec.EXACTLY&& heightMode != MeasureSpec.EXACTLY) {// 修正一下 高度的值 让高度=宽度/比例height = (int) (width / ratio + 0.5f); // 保证4舍五入} else if (widthMode != MeasureSpec.EXACTLY&& heightMode == MeasureSpec.EXACTLY) {// 由于高度是精确的值 ,宽度随着高度的变化而变化width = (int) ((height * ratio) + 0.5f);}// 重新制作了新的规则widthMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY,width + getPaddingLeft() + getPaddingRight());heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY,height + getPaddingTop() + getPaddingBottom());super.onMeasure(widthMeasureSpec, heightMeasureSpec);}}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:itheima="http://schemas.android.com/apk/res/com.itheima.googleplay"android:layout_width="match_parent"android:layout_height="match_parent" ><com.itheima.googleplay.view.RatioLayoutandroid:id="@+id/rl_layout"android:layout_width="match_parent"android:layout_height="wrap_content"android:padding="5dp"itheima:ratio="2.43"><ImageViewandroid:id="@+id/item_icon"android:layout_width="match_parent"android:layout_height="wrap_content"android:scaleType="fitCenter"android:src="@drawable/ic_default" /></com.itheima.googleplay.view.RatioLayout>
标签:
原文地址:http://www.cnblogs.com/liuyu0529/p/4979314.html