第一种是生成圆角背景:
Button mView = (Button)findViewById(R.id.mView); Bitmap myCoolBitmap = ((BitmapDrawable) getResources().getDrawable( R.drawable.icon)).getBitmap(); int w = myCoolBitmap.getWidth(), h = myCoolBitmap.getHeight(); Bitmap rounder = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(rounder); Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG); xferPaint.setColor(Color.RED); canvas.drawRoundRect(new RectF(0, 0, w, h), 20.0f, 20.0f, xferPaint); xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); canvas.drawBitmap(myCoolBitmap, 0, 0, null); canvas.drawBitmap(rounder, 0, 0, xferPaint); Drawable drawable = new BitmapDrawable(rounder); mView.setBackgroundDrawable(drawable);
第二种是真的圆角的位图:
public Bitmap getRoundedCornerBitmap(Bitmap bitmap) { // 创建一个指定宽度和高度的空位图对象 Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); // 用该位图创建画布 Canvas canvas = new Canvas(output); // 画笔对象 final Paint paint = new Paint(); // 画笔的颜色 final int color = 0xff424242; // 矩形区域对象 final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); // 未知 final RectF rectF = new RectF(rect); // 拐角的半径 final float roundPx = 30; // 消除锯齿 paint.setAntiAlias(true); // 画布背景色 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); // 最终在画布上呈现的就是该圆角矩形图片,然后我们返回该Bitmap对象 return output; }