有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓中为透明png图像添加笔划/边框?

我有一些透明的图像,比如形状、字母,我从图库中获取它们,所以我需要给它们黑色的笔划/轮廓,我可以设置边框,但它被设置为整个位图,比如左、右、上、下

Same thing we can do with photoshop is giving outerstroke to image but I want to achieve that in 安卓.

我尝试了{a1}和{a2}这是给边界,但我想做的是如下所示 样本图像

原始图像 without stroke

我想要这样--> With stroke

这在安卓中可能吗


共 (1) 个答案

  1. # 1 楼答案

    我有一个这样的临时解决办法

    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 = (originalBitmap.getWidth() + 2.0f * strokeWidth) / originalBitmap.getWidth();
    float scaleY = (originalBitmap.getHeight() + 2.0f * strokeWidth) / 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_-top使用笔划颜色覆盖原始位图位置绘制颜色(笔划颜色)

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