在开发中经常碰到这样一种情况:要求图片不能变形,宽度为设备屏幕宽度,高度与宽度比例为0.77,因为安卓设备特别杂,所以不能写死,只能动态的匹配.今天就给你一个自定义的ImageView,来彻底解决这个问题,而实现起来是非常简单的
1.自定义控件ZRationImageview的class文件
package com.z.zviewlib;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ImageView;
/**
* Created by Miller Zhang on 2017/2/22.
* desc:
* github:https://github.com/zxyaust CSDN:http://blog.csdn.net/qq_31340657
* Whatever happens tomorrow,we've had today.
*/
public class ZRationImageView extends ImageView {
private float ration;
public ZRationImageView(Context context) {
this(context, null);
}
public ZRationImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ZRationImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ZRationImageView);
ration = array.getFloat(R.styleable.ZRationImageView_ration, 0f);
array.recycle();
setScaleType(ScaleType.FIT_XY);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int width = this.getWidth();
int height = (int) (width * ration);
ViewGroup.LayoutParams layoutParams = getLayoutParams();
layoutParams.width = width;
layoutParams.height = height;
setLayoutParams(layoutParams);
}
}
2.自定义属性
<declare-styleable name="ZRationImageView">
<attr name="ration" format="float"></attr>
</declare-styleable>
3.使用
<com.z.zviewlib.ZRationImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:ration="1"
android:src="@mipmap/ic_launcher" />
大功告成了,你可以设置不同的ration值,试试看,完全没问题.你可以设置src,也可以用background,