相信大家都遇到過ImageView的適配問題,儘管ImageView有多種拉伸方式、fitXY、CenterCrop …… 但仍然無法滿足需求。
如下面這張效果圖,不同分辨率的手機上,無論使用何種拉伸方式都可能會出現變形,這個圖不是純色的,所以圖案變形就不好看了。
對於分辨率適配,通用的一個處理方法就是 按百分比拉伸, 高寬比不變,那麼圖案不會變形,在一定的範圍拉伸/收縮,肉眼看不出模糊,
上代碼,
一、自定義的 按比例展示的ImageView:PercentImageView
package com.thduan.demo;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.iflytek.xmmusic.activitys.R;
import com.kdxf.kalaok.utils.ScreenAdapterUtil;
/**
* 寬高按 比例展示的 圖片
* @author thduan
* 2015-7-2 20:17:31
*/
public class PercentImageView extends ImageView{
private float widthPer;
private float hwPer;
public PercentImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PercentImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.RoomPhotoStyle);
widthPer = ta.getFloat(R.styleable.RoomPhotoStyle_widthPer, 0);
hwPer = ta.getFloat(R.styleable.RoomPhotoStyle_hwPer, 0);
ta.recycle();
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
int widthSize = ScreenAdapterUtil.per2px(widthPer);
int heightSize = (int) (widthSize * hwPer);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
二、自定義兩個屬性
<declare-styleable name="RoomPhotoStyle">
<!-- 寬度佔屏幕的比例 -->
<attr name="widthPer" format="float" />
<!-- 高比寬的比例 -->
<attr name="hwPer" format="float" />
</declare-styleable>
三、佈局中使用
大功告成啦,通過計算高寬比例,可以方便的適配各種機型分辨率, 如果大家有好的適配方法,可以分享出來哦O(∩_∩)O~