想给一张PNG图标用Android代码描边,找不到思路,Google也搜不到方法,只有给文字描边的那种。无奈,网上找到用C#实现的,自己修改了一下,发现工作很完美!
// 这是我的条码制作器的一段函数
public static Bitmap addCenterImage(Bitmap SrcBmp, Bitmap bitmap) {
int width = SrcBmp.getWidth() / 5;
int offsetX = (SrcBmp.getWidth() - bitmap.getWidth()) / 2;
int offsetY = (SrcBmp.getHeight() - bitmap.getHeight()) / 2;
int bmpW = bitmap.getWidth();
int bmpH = bitmap.getHeight();
Canvas ca = new Canvas(bitmap);
Path path = new Path();
for (int i = 0; i < bmpW; i++)
for (int j = 0; j < bmpH; j++) // 这点不透明而且左右上下四点至少有一点是透明的,那这点就是边缘 if (bitmap.getPixel(i, j) != Color.TRANSPARENT && (i > 0 && bitmap.getPixel(i - 1, j) == Color.TRANSPARENT
|| i < bmpW - 1 && bitmap.getPixel(i + 1, j) == Color.TRANSPARENT || j > 0 && bitmap.getPixel(i, j - 1) == Color.TRANSPARENT
|| j < bmpH - 1 && bitmap.getPixel(i, j + 1) == Color.TRANSPARENT))
path.addRect(i - 1, j - 1, i, j, Path.Direction.CCW); // 搜集边缘
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(4.0f);
ca.drawPath(path, paint); // 画出边缘
Canvas canvas = new Canvas(SrcBmp);
canvas.drawBitmap(bitmap, offsetX, offsetY, null);
return SrcBmp;
} |
// 这是我的条码制作器的一段函数
public static Bitmap addCenterImage(Bitmap SrcBmp, Bitmap bitmap) {
int width = SrcBmp.getWidth() / 5;
int offsetX = (SrcBmp.getWidth() - bitmap.getWidth()) / 2;
int offsetY = (SrcBmp.getHeight() - bitmap.getHeight()) / 2;
int bmpW = bitmap.getWidth();
int bmpH = bitmap.getHeight();
Canvas ca = new Canvas(bitmap);
Path path = new Path();
for (int i = 0; i < bmpW; i++)
for (int j = 0; j < bmpH; j++) // 这点不透明而且左右上下四点至少有一点是透明的,那这点就是边缘 if (bitmap.getPixel(i, j) != Color.TRANSPARENT && (i > 0 && bitmap.getPixel(i - 1, j) == Color.TRANSPARENT
|| i < bmpW - 1 && bitmap.getPixel(i + 1, j) == Color.TRANSPARENT || j > 0 && bitmap.getPixel(i, j - 1) == Color.TRANSPARENT
|| j < bmpH - 1 && bitmap.getPixel(i, j + 1) == Color.TRANSPARENT))
path.addRect(i - 1, j - 1, i, j, Path.Direction.CCW); // 搜集边缘
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(4.0f);
ca.drawPath(path, paint); // 画出边缘
Canvas canvas = new Canvas(SrcBmp);
canvas.drawBitmap(bitmap, offsetX, offsetY, null);
return SrcBmp;
}
以上代码的效果如下!
条码制作器的描边函数演示
下一版本的《条码制作器》将提供此功能,并修复PNG小图片添加后造成背景变黑的问题!
Android给PNG描边