如何在android中为透明png图像添加描边/边框?

a.d*_*dev 7 java png android bitmap android-canvas

我有透明的图像,如形状,我从图库中获取的字母,所以我需要用黑色给它们描边/轮廓,我可以设置边框,但它被设置为整个位图,如左、右、顶部和底部。

我们可以用 photoshop 做的同样的事情是给图像外部描边,但我想在 android 中实现这一点。

我试过这个是给边界,但我想做的是像下面的示例图像

原图 无中风

我想要这样--> 有中风

这在android中可能吗?

Meh*_*ren 3

我有一个这样的临时解决方案

int strokeWidth = 8;
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.flower_icon);
Bitmap newStrokedBitmap = Bitmap.createBitmap(originalBitmap.getWidth() + 2 * strokeWidth, originalBitmap.getHeight() + 2 * strokeWidth, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newStrokedBitmap);
float scaleX = newStrokedBitmap.getWidth() / originalBitmap.getWidth();
float scaleY = newStrokedBitmap.getHeight() / originalBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY);
canvas.drawBitmap(originalBitmap, matrix, null);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_ATOP); //Color.WHITE is stroke color
canvas.drawBitmap(originalBitmap, strokeWidth, strokeWidth, null);
Run Code Online (Sandbox Code Playgroud)

首先创建一个新的位图,其笔画大小分别为左、右、下、上。

其次,一点位图并在新创建的位图画布上绘制缩放的位图。

使用PorterDuff模式绘制颜色(您的描边颜色)SRC_ATOP使用描边颜色覆盖原始位图位置。

最后在新创建的位图画布上绘制原始位图。