Michal
Michal

Reputation: 3642

Android: How to draw line with rounded corner?

How can I draw line/arc with rounded corners as you can see on the picture below? I need to draw this on Canvas.

enter image description here

Upvotes: 4

Views: 6701

Answers (1)

natario
natario

Reputation: 25194

I think you can workaround this by drawing three lines with a partial overlap:

  • two external lines with Paint.Cap.ROUND
  • one inner line with Paint.Cap.BUTT

Assuming your input data is

float lineWidth = 20;
float lineRadius = 100;
float cornerRadius = 2;

You go as follows,

float width, radius;
// Draw outer lines
paint.setStrokeCap(Paint.Cap.ROUND);
width = cornerRadius * 2;

// Draw inner
radius = lineRadius - lineWidth/2f + cornerRadius;
canvas.draw(...)

// Draw outer
radius = lineRadius + lineWidth/2f - cornerRadius;
canvas.draw(...)

// Draw center
paint.setStrokeCap(Paint.Cap.BUTT);
width = lineWidth - 2f*cornerRadius;
radius = lineRadius;
canvas.draw(...)

You might need to slightly alter the arc angle for the center line (it must be cornerRadius longer, on each side) but that is easy.

Upvotes: 8

Related Questions