Is there any way to join lines with arcs, creating...
# compose
j
Is there any way to join lines with arcs, creating a radius? It seems to be possible to join straight lines but I have two arcs that need to join two lines. I've tried to solve the problem mathematically and calculating exactly where the corner arcs should go and what start and sweep angles they should have, but that is proving to be quite difficult. The shape I'm going for is what's marked with the red dots in this image. There needs to be a radius on those corners.

https://i.imgur.com/pvzMByH.png

r
You want the intersection of lines with the arcs to have 4 rounded corners?
I’m not entirely sure what it would look like since there’s no guarantee the dashes will intersect at those points
Do you have a mock of the final result?
j
4 rounded corners at the position of the red dots yes
Yes give me a second

https://i.imgur.com/vNrkkkX.png

Something like this. This is actually my current preview, but the radiuses aren't exact. They are mathematically wrong, even though it looks sort of fine.
I did this by placing the corner arcs myself
I would like to avoid that if possible since it was far more mathematically intense than I anticipated and the final solution is still incorrect.
r
Aaah I see ok, not what I was expecting.
So there is a way, give me one second
I don’t think we’ve exposed this in Compose but you can grave the
nativeCanvas
and an
android.graphics.Paint
to achieve this
You set a
CornerPathEffect
on the
Paint
as a
PathEffect
You might even be able to combine it with the
DashPathEffect
using https://developer.android.com/reference/android/graphics/ComposePathEffect
That way you just draw an arc, using a
ComposePathEffect
containing a
DashPathEffect
+
CornerPathEffect
to get a fill
Path
that’s your arc with the dashes
then you draw that with the
CornerPathEffect
j
I tried something similar I believe. I used canvas.drawOutline as per this post: https://www.geeksforgeeks.org/create-polygons-with-rounded-corners-in-android-using-jetpack-compose/
It wont join the arcs properly. When I read the cornerPathEffect documentation it says that it joins line segments, not arc segments.
r
It works on sharp angles
It has nothing to do with lines vs arcs
So it should work on the dashes
j
Ok. I'm getting a weird result with it. Would it be possible to show an example of how you propose to do it? I've been trying for many days already...
r
Try the
getFillPath
approach I mentioned
k
Are you asking how to create a path for each one of these green pieces?
j
Yes
k
Connecting the straight segments to the curved segments?
j
Exactly
I'll send you what I have at the moment. Not sure how to best combine drawWithCache and still be able to use a canvas to access drawOutline.
Copy code
androidx.compose.foundation.Canvas(
    modifier = modifier
        .then(Modifier.size(500.dp))
        .drawWithCache {

            val paths = mutableListOf<Path>()
            val outerRadius = min(size.width, size.height) / 2
            val currentThickness = thickness(outerRadius)
            val currentCornerRadius = cornerRadius(outerRadius)
            val sweepAng = (2 * PI / indicatorCount - gapAng).toFloat()

            for (idx in 0 until indicatorCount) {
                val ang =
                    (idx / indicatorCount.toFloat() * 2 * PI - PI / 2 - gapAng / 2 + 2 * PI / indicatorCount).toFloat()

                val path = Path()
                path.arcToRad(
                    Rect(
                        -outerRadius + currentThickness,
                        -outerRadius + currentThickness,
                        outerRadius - currentThickness,
                        outerRadius - currentThickness
                    ).translate(outerRadius, outerRadius),
                    ang,
                    -sweepAng,
                    false
                )
                path.arcToRad(
                    Rect(-outerRadius, -outerRadius, outerRadius, outerRadius)
                        .translate(outerRadius, outerRadius),
                    ang - sweepAng,
                    sweepAng,
                    false
                )
                path.close()

                paths.add(path)
            }

            onDrawWithContent {
                drawIntoCanvas { canvas ->
                    paths.forEach { path ->
                        canvas.drawOutline(
                            outline = Outline.Generic(path),
                            paint = Paint().apply {
                                color = colors.backgroundColor
                                pathEffect =
                                    PathEffect.cornerPathEffect(currentCornerRadius)
                            }
                        )
                    }
                }
            }
        }
) {

}
This looks like this:

https://i.imgur.com/TVEibyh.png

r
You don’t need to build all those segments yourself
You can dash a circle/arc to get the segments
j
The joins aren't working when I draw my arcs, but they work when they are lines.
r
You only need to build them if you want to create the rounded corners yourself
j
I don't understand. "dash"?
r
Drawing a path with dashes
That’s what you are doing
j
Ah. Yes that's true
r
So hopefully you can just dash the arc + apply the corner effect
And if that doesn’t work then you’ll have to do the math
(there is potentially another way but I don’t know whether it’ll work well)
j
So I would just have 2 ovals and when I draw them I somehow apply a dash effect along with the corner effect?
r
No, just 1 oval
You stroke that oval with a dash effect + corner radius effect
j
Oh I see
r
which you can combine using the compose effect I linked to above
And if composing the effects doesn’t work
you can use
Paint.getFillPath
to get your dashed oval as a path meant to be filled
and you can apply the corner effect to that
k
Here’s a diagram that shows how to find the center of an arc that connects a straight segment to a circular arc
Point H lies 10 away from AB, and when you center the connecting arc of radius 10 in it, it will connect to the larger arc BC preserving the tangent continuity
In case you decide to go fully custom
You’ll need to do this same technique for each one of the four corners of each segment
j
Thanks a lot, I will look into that solution in case the automatic method fails. Much cleaner than what I was trying to do.
What throws me off as well is that it's not just one shape with 4 corners, but a circle of them, so that has to be accounted for.
k
Sure, in this case your big arc (BC) stays the same, but your line (AB) is different, so when you draw that parallel line (FG) to find the intersection with the smaller arc (ED), your FG moves as well
r
Note you also need to build only 1 of those shapes
if you build it as a
Path
you can just use a canvas rotation to draw it all around your circle
k
The idea is the same - you draw a line X units away from your straight line, and a circle X units aways from your circular arc. The intersection will give you the center point of the connecting arc
r
or… use a
PathDashPathEffect
to stamp it along the arc!
j
I was thinking of that as well Romain. That's probably much simpler than doing it with sin and cosine yourself.
I'm trying that now Romain. 🙂
r
watch this
I go through demos of all those Path APIs
start around 18:46
Exmaple:
Screenshot 2023-02-10 at 10.09.43 AM.png
(it’s called
stampedPathEffect
in Compose)
actually now that I think about it…
maybe you don’t need any fancy math. You could try to use
stampedPathEffect
with a simple rounded rect, using the
morph
stamp effect
it might do what you want (the corners might be morphed but if your radius is not too big it might not be noticeable)
k
And this is for connecting the other side. It works both ways with the same line FG, once with a smaller arc, and once with a large arc.
There are some (longish) Youtube videos on these general engineering drawing problems, under the name of “tangent problems”
(in case you want to have full control of the visuals)
j
Thank you, that might come in handy.
By the way @romainguy this does not apply any radius:
Copy code
drawPath(
    path = path,
    brush = SolidColor(colors.backgroundColor),
    style = Stroke(
        currentThickness,
        pathEffect = PathEffect.chainPathEffect(
            PathEffect.dashPathEffect(floatArrayOf(50f, 20f)),
            PathEffect.cornerPathEffect(20f)
        )
    )
)
r
Try the stampedPathEffect + rounded rect + morph then
And if that still doesn’t work, do what Kirill showed you + stampedPathEffect
j
@Kirill Grouchnikov I'm looking into your solution now. Still don't understand how you're supposed to get the X position of H in the first image. Sure, Y is easy enough at 10, but how do you get X? Do you have to find the intersection of FG with the arc?
And will the sweep angle of this arc always be 90 degrees?
I saw your previous message now. So it's a line to circle intersection computation.
k
Yes, it’s that. That part is easy since Y is fixed. It’s going to get a bit more complex to determine the start angle and arc span for the connector.
If you go down that road, you have two straight segments, two big arcs (outer and inner) and four connector arcs. Each one needs to be quite specific on its start / end so that it all feels like one continuous shape.
j
If the arcs are always 90 degrees, I believe I could find the points for the bigger arcs
k
I don’t think they are going to be 90 degrees. It’s slightly less for the outer corners, and slightly more for the inner ones.
In both cases D is slightly to the right of H.
j
Alright. Well this is a lot trickier than it should be!
k
I’d say it’s the usual amount of math for custom paths
j
Should be possible to just join segments with a radius
Idk. Our iOS developer hade a path joining option which seemed to do the trick.
I'm thinking of only drawing the corner arcs
Closing the path with lines
with path.close()
Then cutting the paths with 2 large circle paths
or clipping rather
I still need to know the sweep angle of the corner arcs though, so nevermind.
r
Did you try the stamped path idea with a round rect?
j
@romainguy I did not as I didn't quite understand it, plus you seemed unsure that it would work or give an accurate result.
Right now I'm working on the line to circle intersection. I think I may be able to figure out the proper start angle and sweep angle after that.
r
So the idea is you create a Path that contains a round rect
Then you draw the oval with a stamped path effect that uses that round rect
If you set the stamp style to morph, the rounded rect will bend to follow the oval and be repeated along the oval
j
Interesting. I'm worried that it wont bend appropriately to create the desired corners however.
r
It will bend appropriately but it might be too much and distort the corners. Worth a try though
j
Yeah I might try it eventually. Kind of commited to the path solution for the moment though.
Thanks for the suggestion
I've started to apply @Kirill Grouchnikovs solution, but still very early stages. Got some debugging lines and found the H point of intersection for the bottom left arc. (yellow dot)

https://i.imgur.com/tcF9YhB.png

k
Upload your images here so that they can be zoomed without going to an external site
j
There
k
Going to be easier to see what's up if you do larger sizes for the segments. Once you have those done, you can then do the smaller ones
j
Sorry, missed your message. Yes, that's true and I realized it on my own. The radius is a bit larger now. Also, I successfully created the first arc.
k
Nice
j
I added extension methods for calculating dot product, angle between vectors, intersections, etc. After I had the center I then found the two corners of the arc. The top left one was simply set to the circle center - radius. The bottom one I calculated by line to arc intersection. Then I pointed a vector to the right side of the circle from the center and calculated the angle to the bottom most point for the start angle. Then I calculated the angle between the two blue points as the sweep angle.
Does it seem accurate?
k
Seven more pieces to go 😃
j
I believe 5. The lines are created when the path is closed.
k
Close goes from the last point to the first. It doesn't close all the jumps in the middle
j
Yes I thought so, but closing two arcs will add lines at the sides
k
Wouldn't really save you much, since you need to compute the first point coordinates in any case
j
Yes. I'm thinking that maybe there is some time saving possibilities elsewhere though
The inner arc angle should be the same for the other corner right?
And inner sweep angle is just (sweep angle - angle to top left blue circle * 2)
I feel like drawing the next two parts could be quite simple in that case.
k
The inners are identical. The outers are identical too.
j
My logic should work then right?
Instead of doing all of this complicated math again, I could do simple angle subtraction for the inner large circle and re-use the other sweep-angle for the corner
e
the math isn't that bad, I think
👏 1
image.png
my first attempt was garbage, but the problem was my assumption that angles go counter-clockwise (they don't). just had to swap a bunch of things around and then it was fine
j
Very nice @ephemient. I've been bashing my head against this problem for close to a week and you manage to come up with a quite simple solution in no time. If you don't mind, I will use your solution. The code is clean too.
e
go for it. the code's not that clean, but it should be easy enough to tweak to whatever you need.
165 Views