如何以编程方式向可绘制对象添加描边?

How to add a stroke to a drawable programatically?

我有这个代码:

我的可绘制对象包裹了另一个可绘制对象(圆形)。

如何以编程方式向内部可绘制对象添加描边?

public final class HighlightCircleDrawable extends Drawable implements Drawable.Callback {

  private final Drawable toHighlight;
  private final Paint paint = new Paint();

//...

  public HighlightCircleDrawable(Drawable toHighlight) {
    this.toHighlight = toHighlight;
    toHighlight.setCallback(this);
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.GRAY);
  }

  @Override
  public void draw(Canvas canvas) {
    canvas.drawOval(pulseBounds, paint);
    toHighlight.draw(canvas);
  }

首先,您需要制作背景,为此您应该使用整个 canvas。从填充 canvas 开始,然后应用填充,但关键是为 backgroundPaint 使用较小的边界,以便 borderPaint 包围 highlightPaint

final Paint borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.FILL);
borderPaint.setColor(borderColor);
borderPaint.setAntiAlias(true);
borderPaint.setDither(true);

...

canvas.drawOval(rect, borderPaint);
canvas.drawOval(pulseBounds, paint);