1. 程式人生 > >Android--›圓角圖片,圓角任意View,圓角父佈局Layout(任意形狀的View且超簡潔實現)

Android--›圓角圖片,圓角任意View,圓角父佈局Layout(任意形狀的View且超簡潔實現)

相信大家對圓角圖片已經非常熟悉了,但是圓角任意View,和圓角父佈局,甚至是任意形狀的View,肯定還是比較陌生的.

今天就揭開她的面紗.

//通常情況下,圓角圖片是這樣的...
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx,
		int number) {
	int w = bitmap.getWidth();
	int h = bitmap.getHeight();
	Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
	Canvas canvas = new Canvas(output);
	final int color = 0xdd424242;
	final Paint paint = new Paint();
	final Rect rect = new Rect(0, 0, w, h);
	final RectF rectF = new RectF(rect);
	paint.setAntiAlias(true);
	number = number * 255 / 100;
	paint.setAlpha(number);
	canvas.drawARGB(0, 0, 0, 0);
	paint.setColor(color);
	canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
	paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	canvas.drawBitmap(bitmap, rect, rect, paint);
	return output;
}

上圖為證:
這裡寫圖片描述

其實最核心的程式碼,就一行.(真的是對得起標題, 超簡潔的實現啊…)
在View的draw方法中,加入:(這個方法可以在任意一個View的子類中新增,包括ImageView)

@Override
public void draw(Canvas canvas) {
	//roundPath是什麼形狀,繪製出來的Layout就是什麼形狀的....相當於任意View了.
    canvas.clipPath(roundPath);//一篇文章就是為了這一樣程式碼....
    super.draw(canvas);
}

以下是我的使用方式:

public class RoundLayout extends RelativeLayout {
 private float roundLayoutRadius = 14f;
 private Path roundPath;
 private RectF rectF;

 public RoundLayout(Context context) {
     this(context, null);
 }

 public RoundLayout(Context context, AttributeSet attrs) {
     super(context, attrs);

     TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundLayout);
     roundLayoutRadius = typedArray.getDimensionPixelSize(R.styleable.RoundLayout_roundLayoutRadius, (int) roundLayoutRadius);
     typedArray.recycle();

     init();
 }

 private void init() {
     setWillNotDraw(false);//如果你繼承的是ViewGroup,注意此行,否則draw方法是不會回撥的;
     roundPath = new Path();
     rectF = new RectF();
 }

 private void setRoundPath() {
	 //新增一個圓角矩形到path中, 如果要實現任意形狀的View, 只需要手動新增path就行
     roundPath.addRoundRect(rectF, roundLayoutRadius, roundLayoutRadius, Path.Direction.CW);
 }


 public void setRoundLayoutRadius(float roundLayoutRadius) {
     this.roundLayoutRadius = roundLayoutRadius;
     setRoundPath();
     postInvalidate();
 }

 @Override
 protected void onLayout(boolean changed, int l, int t, int r, int b) {
     super.onLayout(changed, l, t, r, b);
     rectF.set(0f, 0f, getMeasuredWidth(), getMeasuredHeight());
     setRoundPath();
 }

 @Override
 public void draw(Canvas canvas) {
     if (roundLayoutRadius > 0f) {
         canvas.clipPath(roundPath);
     }
     super.draw(canvas);
 }
}

ImageView的圓角,其實也是那一行程式碼可以搞定的.不闡述了,快快行動,用行動證明自己吧.

原始碼參考

補充:
上述方法會有明顯的鋸齒情況,因為Paint才提供抗鋸齒方法.

至此: 文章就結束了,如有疑問: QQ群:274306954 歡迎您的加入.