先来见效果图:
如果想向上图展示的那样,实现图片或是控件按照宽高比例进行显示,当然最先想到的是用weight,但是又一想weight只适用于屏幕宽度按比例分配,但是高度要怎么设置呢,所以weight方法不行。
那应该用什么方法呢,能做到宽:高=4:3的比例显示?所以想到了自定义控件:
step1:首先自定义一个名叫LoweImageView的类:
<pre name="code" class="java">public class LoweImageView extends ImageView {
/**
* 图片比例. 比例=宽/高
*/
private float mRatio;
public LoweImageView(Context context) {
this(context, null);
}
public LoweImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LoweImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
/**
* 初始化
*
* @param context
* 上下文
* @param attrs
* 属性
*/
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.LoweImageView);
mRatio = typedArray.getFloat(R.styleable.LoweImageView_ratio, 0);
typedArray.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 宽模式
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
// 宽大小
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
// 高大小
int heightSize;
// 只有宽的值是精确的才对高做精确的比例校对
if (widthMode == MeasureSpec.EXACTLY && mRatio > 0) {
heightSize = (int) (widthSize / mRatio + 0.5f);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,
MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
step2:上面代码中的R.styleable.LoweImageView、R.styleable.LoweImageView_ratio是不是不知道在哪呢?我来告诉你吧,在res/values/attrs文件中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LoweImageView">
<!-- 比例=宽/高 -->
<attr name="ratio" format="float" />
</declare-styleable>
</resources>
step3:最后一步就是在xml中引用了:
<com.qing.autolayout.LoweImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/picture"
app:ratio="1.333" />
其中1.333就是你需要设置的宽:高的float型比例(当然,可以改成你需要的比例)。现在开始Run你的项目,就会出现宽高按比例的显示。
总之,就是只要宽的长度确定了,那么高度就会按照你设置的比例进行显示。上面是ImageView的示例,当然可以把ImageView换成Button、LinearLayout、RelativeLayout等等等,都是相同的道理。
另外,附上源码下载地址:demo地址