Android 中设置 Bitmap 任意角度

Android 中设置 Bitmap 任意角度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class BitmapUtils
{
public static Bitmap fillet(Bitmap bitmap, int roundPx,
boolean topLeft, boolean topRight, boolean bottomLeft, boolean bottomRight)
{
try
{
// 其原理就是:先建立一个与图片大小相同的透明的Bitmap画板
// 然后在画板上画出一个想要的形状的区域。
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();

Bitmap paintingBoard = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(paintingBoard);
canvas.drawARGB(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT);

final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);

//画出4个圆角
final RectF rectF = new RectF(0, 0, width, height);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

//把不需要的圆角去掉
if (topLeft)
{
clipTopLeft(canvas, paint, roundPx, width, height);
}
if (topRight)
{
clipTopRight(canvas, paint, roundPx, width, height);
}
if (bottomLeft)
{
clipBottomLeft(canvas, paint, roundPx, width, height);
}
if (bottomRight)
{
clipBottomRight(canvas, paint, roundPx, width, height);
}
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

final Rect src = new Rect(0, 0, width, height);
final Rect dst = src;
canvas.drawBitmap(bitmap, src, dst, paint);
return paintingBoard;
} catch (Exception exp)
{
return bitmap;
}
}

private static void clipTopLeft(final Canvas canvas, final Paint paint, int offset, int width, int height) {
final Rect block = new Rect(0, 0, offset, offset);
canvas.drawRect(block, paint);
}

private static void clipTopRight(final Canvas canvas, final Paint paint, int offset, int width, int height) {
final Rect block = new Rect(width - offset, 0, width, offset);
canvas.drawRect(block, paint);
}

private static void clipBottomLeft(final Canvas canvas, final Paint paint, int offset, int width, int height) {
final Rect block = new Rect(0, height - offset, offset, height);
canvas.drawRect(block, paint);
}

private static void clipBottomRight(final Canvas canvas, final Paint paint, int offset, int width, int height) {
final Rect block = new Rect(width - offset, height - offset, width, height);
canvas.drawRect(block, paint);
}
}
------ 本文结束,欢迎阅读------
欢迎关注公众号,不定期更新