如何使用 Canvas 为位图图像内容添加边框而不是其背景?

How to add border to bitmap image content instead of its background by using Canvas?

位图图像的特点是它具有透明背景,通常具有矩形形状,所以当我们尝试为图像添加边框,而不是它的内容里面会有边框,它的背景会有边框。例如,我有一张狗的位图图像,我希望它有一个 border,但是矩形背景将有一个 border。我正在使用 Canvas 绘制位图,但遇到了这个问题。谁能帮帮我?

创建照片的块代码

  mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeWidth(10); // set stroke width
    mPaint.setColor(getResources().getColor(R.color.black)); // set stroke color
    mPaint.setAntiAlias(true);
    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icons8_bus_36_2);
    tempBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas tempCanvas = new Canvas(tempBitmap);
    Rect rect = new Rect(
            10 / 2,
            10 / 2,
            tempCanvas.getWidth() - 10 / 2,
            tempCanvas.getHeight() - 10 / 2);
    tempCanvas.drawRect(rect,mPaint);
    tempCanvas.drawBitmap(bitmap, 0, 0, mPaint);

关于这部分:

Rect rect = new Rect(
            10 / 2,
            10 / 2,
            tempCanvas.getWidth() - 10 / 2,
            tempCanvas.getHeight() - 10 / 2);

改为

Rect rect = new Rect(
            10 / 2,
            10 / 2,
            (tempCanvas.getWidth() - 10) / 2,
            (tempCanvas.getHeight() - 10) / 2);

那是因为10先除以2

此外,在绘制矩形之前先绘制位图

你可以用这个画画:

Path clipPath = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);