1. 程式人生 > >Android 自定義上面圓角下面直角的ImageView

Android 自定義上面圓角下面直角的ImageView

今天在群裡面有人問我怎樣實現一張圖片上面是圓角下面是直角?

類似於這樣的圖片:


之前用過RoundImageView,其實就是自定義ImageView。想了一下自己重新畫一下圖片不就ok了麼?再給佈局設定一個圓角效果。好了我們來看一下原始碼:

1.首先我們自定義RoundImageView繼承於ImageView

public class RoundedImageView extends ImageView {

	/*圓角的半徑,依次為左上角xy半徑,右上角,右下角,左下角*/
	private float[] rids = {10.0f,10.0f,10.0f,10.0f,0.0f,0.0f,0.0f,0.0f,};

	public RoundedImageView(Context context) {
		super(context);
	}

	public RoundedImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}


	/**
	 * 畫圖
	 * by Hankkin at:2015-08-30 21:15:53
	 * @param canvas
	 */
	protected void onDraw(Canvas canvas) {
		Path path = new Path();
		int w = this.getWidth();
		int h = this.getHeight();
		/*向路徑中新增圓角矩形。radii陣列定義圓角矩形的四個圓角的x,y半徑。radii長度必須為8*/
		path.addRoundRect(new RectF(0,0,w,h),rids,Path.Direction.CW);
		canvas.clipPath(path);
		super.onDraw(canvas);
	}
}
然後我們定義一個圓角的半徑陣列,依次為左上角x,y半徑、右上角、右下角、左下角

接下來我們就自己畫一下imageview

我們給路徑新增圓角矩形,將我們定義的圓角半徑設定進去,給canvas切割一下畫布就可以了。imageview就畫成了上面是圓角,下面是直角了。如果需要圖片的四個角為不同的直角圓角,只需要改一下我們的圓角半徑值就可以了。

2.然後我們再給佈局設定一下圓角,

我們自定義一個round.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="#fff" />
  <corners android:topLeftRadius="5dp"
           android:topRightRadius="5dp"
           android:bottomRightRadius="5dp"
           android:bottomLeftRadius="5dp"/>
</shape>
設定一下上下左右的圓角半徑,然後設定一下佈局的background就ok了

比較簡單,如果想要詳細學習自定義圓角圖片,推薦大家可以學習一下洪洋的

這兩篇文章,還是比較不錯的