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"
	/>


使用請謹慎,本例沒有考慮性能方面的東西,謹慎再謹慎。

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