如何在Android中给透明PNG图像添加描边/边框?

7
我有一些透明的图形和字母图片,它们来自画廊,所以我需要用黑色给它们描边/轮廓,我可以设置边框,但它会覆盖整个位图,例如左侧、右侧、顶部和底部。
同样的事情我们可以在Photoshop中做,就是给图像外部加描边,但我想在Android中实现这个效果。
我尝试了thisthis,它们都会给出边框,但我想要的是下面这样的效果:
原始图片 without stroke 我想要的是这样的效果--> With stroke 在Android中是否可能实现这个效果?
1个回答

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);

首先,在左侧、右侧、底部和顶部创建一个带有描边大小的新位图。
其次,略微缩小位图,并在新创建的位图画布上绘制缩放后的位图。
使用PorterDuff模式SRC_ATOP,以描边颜色绘制颜色覆盖原始位图位置。
最后,在新创建的位图画布上绘制您的原始位图。
"最初的回答"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接