Android 圆形图片加白边加阴影
/** * 将图片准转为圆形 * * @param bitmap * @return */ public static Bitmap getRoundedCornerBitmap(String path, Bitmap bitmap) { int size = bitmap.getWidth() < bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight(); Bitmap output = Bitmap.createBitmap(size, size, Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, size, size); final float roundPx = size / 2; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawCircle(roundPx, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); ImageCruCache.getInstance().addBitmapToMemoryCache(path, output); return getRoundeBitmapWithWhite(path, output); } /** * 获取白色边框 * * @param path * @param bitmap * @return */ public static Bitmap getRoundeBitmapWithWhite(String path, Bitmap bitmap) { int size = bitmap.getWidth() < bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight(); int num = 14; int sizebig = size + num; Bitmap output = Bitmap.createBitmap(sizebig, sizebig, Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = Color.parseColor("#FFFFFF"); final Paint paint = new Paint(); final float roundPx = sizebig / 2; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawBitmap(bitmap, num / 2, num / 2, paint); paint.setXfermode(new PorterDuffXfermode(Mode.DST_ATOP)); RadialGradient gradient = new RadialGradient(roundPx, roundPx, roundPx, new int[] { Color.WHITE, Color.WHITE, Color.parseColor("#AAAAAAAA") }, new float[] { 0.f, 0.97f, 1.0f }, Shader.TileMode.CLAMP); paint.setShader(gradient); canvas.drawCircle(roundPx, roundPx, roundPx, paint); ImageCruCache.getInstance().addBitmapToMemoryCache(path, output); return output; }
分两步执行,第一步:getRoundedCornerBitmap方法执行将图片转换为正圆;
第二部:getRoundeBitmapWithWhite设置白色边框并且添加阴影
如果不喜欢阴影,可以考虑去掉paint的阴影效果
这里有一个非常重要的事情:createBitmap一定要使用 Config.ARGB_8888 不然就没有效果。具体原因有待研究。