Search code examples
androidandroid-canvasandroid-drawablestroke

How to add a stroke to a drawable programatically?


I have this code:

My drawable wraps another drawable (circular).

How can I add a stroke to the inner 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);
  }

Solution

  • First, you need to make the background, you should use the entire canvas for this. Start with filling the canvas, then applying your fill, but the key is to use smaller bounds for the backgroundPaint so the borderPaint surrounds the 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);