android: RoundCornerImageView 图片视图 倒圆角

需求:固定大小的ImageView,但是大小不固定的ImageBitmap,想要使用这个大小不一的ImageBitmap填充满这个ImageView,从而让整个视图看起来整齐

这个可以直接在layout.xml这样实现的

<ImageView android:id="@+id/foodItem_foodImg"
		android:src="@drawable/food_img_na"
		android:layout_width="277dip"
		android:layout_height="300dip"
		android:scaleType="centerCrop"
	/>

这里边的centerCrop的意思就是:Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). 英语撇,就不翻译了,见谅。

参见:Developer.android.com


但是这样的图片看起来是有直角的,是生硬的,给用户一种强硬的感觉。

如果我们把图片的4个角都给他倒圆角,就看起来圆润一些,不至于那么伤人,那么生硬。

但是我想了很久,也找了很久,也没有找到直接操作ImageBitmap来实现:centerCrop效果 + 圆角效果

后来想到直接在在ImageView.onDraw的时候,给他画出圆角来,这样这个ImageView里面的ImageBitmap也有圆角的效果了

代码是这样实现的


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundCornerImageView extends ImageView {

	public RoundCornerImageView(Context context) {
		super(context);
	}
	
	public RoundCornerImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public RoundCornerImageView(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		Path clipPath = new Path();
		int w = this.getWidth();
		int h = this.getHeight();
		clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);
		canvas.clipPath(clipPath);
		super.onDraw(canvas);
	}
}

下面这行代码就能画出圆角效果,10度的角
clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);

在layout.xml中直接使用RoundCornerImageView就会出现圆角的ImageView效果

<cn.hus.app.ui.utils.RoundCornerImageView android:id="@+id/foodItem_foodImg"
		android:src="@drawable/food_img_na"
		android:layout_width="277dip"
		android:layout_height="300dip"
		android:scaleType="centerCrop"
	/>


使用请谨慎,本例没有考虑性能方面的东西,谨慎再谨慎。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章