Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 355
Michal Avatar asked Oct 20 '25 19:10

Michal


1 Answers

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.

like image 99
natario Avatar answered Oct 23 '25 09:10

natario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!