创建圆角图片的方式大同小异,最简单的就是 9.png 美工做出来的就是,这样的最省事直接设置即可。
第二种就是通过裁剪
这里的剪裁指的是根据原图我们自己生成一张新的bitmap,这个时候指定图片的目标区域为一个圆角局域。这种做法有一点需要生成一个新的bitmap,所以会消耗至少2倍的图片内存,
下面分析一下代码的含义:
a.首先创建一个指定高宽的bitmap,作为输出的内容,
b.然后创建一个相同大小的矩形,利用画布绘制时指定圆角角度,这样画布上就有了一个圆角矩形。
c.最后就是设置画笔的剪裁方式为Mode.SRC_IN,将原图叠加到画布上,
这样输出的bitmap就是原图在矩形局域内的内容。
/** * 图片圆角 * @param bitmap * @return */ public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); final float roundPx = 12; 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.recycle(); return output; }
那第三种呢就是利用BitmapShader
int widthLimit = 96; int heightLimit = 96; Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), imageId), 96,96, false); BitmapShader shader; shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setShader(shader); RectF rect = new RectF(0.0f, 0.0f, widthLimit, heightLimit); // rect contains the bounds of the shape // radius is the radius in pixels of the rounded corners // paint contains the shader that will texture the shape Bitmap output = Bitmap.createBitmap(widthLimit, heightLimit, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); canvas.drawRoundRect(rect, 12, 12, paint); //drawable = context.getResources().getDrawable(imageId); //drawable = new BitmapDrawable(ImageUtil.drawImageDropShadow(tmp)); // Log.i(TAG, "======>>>>>> "+context.getPackageName() + " imageId:" + imageId); // drawable = new BitmapDrawable(BitmapFactory.decodeResource(context.getResources(), imageId)); drawable = new BitmapDrawable(output); bitmap.recycle();