https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
j

Jonny

02/10/2023, 5:06 PM
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

romainguy

02/10/2023, 5:18 PM
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

Jonny

02/10/2023, 5:18 PM
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

romainguy

02/10/2023, 5:26 PM
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

Jonny

02/10/2023, 5:30 PM
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

romainguy

02/10/2023, 5:31 PM
It works on sharp angles
It has nothing to do with lines vs arcs
So it should work on the dashes
j

Jonny

02/10/2023, 5:32 PM
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

romainguy

02/10/2023, 5:33 PM
Try the
getFillPath
approach I mentioned
k

Kirill Grouchnikov

02/10/2023, 5:34 PM
Are you asking how to create a path for each one of these green pieces?
j

Jonny

02/10/2023, 5:34 PM
Yes
k

Kirill Grouchnikov

02/10/2023, 5:34 PM
Connecting the straight segments to the curved segments?
j

Jonny

02/10/2023, 5:34 PM
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.
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

romainguy

02/10/2023, 5:46 PM
You don’t need to build all those segments yourself
You can dash a circle/arc to get the segments
j

Jonny

02/10/2023, 5:46 PM
The joins aren't working when I draw my arcs, but they work when they are lines.
r

romainguy

02/10/2023, 5:46 PM
You only need to build them if you want to create the rounded corners yourself
j

Jonny

02/10/2023, 5:47 PM
I don't understand. "dash"?
r

romainguy

02/10/2023, 5:48 PM
Drawing a path with dashes
That’s what you are doing
j

Jonny

02/10/2023, 5:48 PM
Ah. Yes that's true
r

romainguy

02/10/2023, 5:49 PM
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

Jonny

02/10/2023, 5:54 PM
So I would just have 2 ovals and when I draw them I somehow apply a dash effect along with the corner effect?
r

romainguy

02/10/2023, 5:54 PM
No, just 1 oval
You stroke that oval with a dash effect + corner radius effect
j

Jonny

02/10/2023, 5:55 PM
Oh I see
r

romainguy

02/10/2023, 5:55 PM
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

Kirill Grouchnikov

02/10/2023, 5:59 PM
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

Jonny

02/10/2023, 6:03 PM
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

Kirill Grouchnikov

02/10/2023, 6:05 PM
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

romainguy

02/10/2023, 6:06 PM
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

Kirill Grouchnikov

02/10/2023, 6:06 PM
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

romainguy

02/10/2023, 6:06 PM
or… use a
PathDashPathEffect
to stamp it along the arc!
j

Jonny

02/10/2023, 6:06 PM
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

romainguy

02/10/2023, 6:07 PM
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

Kirill Grouchnikov

02/10/2023, 6:20 PM
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

Jonny

02/10/2023, 6:23 PM
Thank you, that might come in handy.
By the way @romainguy this does not apply any radius:
drawPath(
    path = path,
    brush = SolidColor(colors.backgroundColor),
    style = Stroke(
        currentThickness,
        pathEffect = PathEffect.chainPathEffect(
            PathEffect.dashPathEffect(floatArrayOf(50f, 20f)),
            PathEffect.cornerPathEffect(20f)
        )
    )
)
r

romainguy

02/10/2023, 6:26 PM
Try the stampedPathEffect + rounded rect + morph then
And if that still doesn’t work, do what Kirill showed you + stampedPathEffect
j

Jonny

02/10/2023, 8:22 PM
@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

Kirill Grouchnikov

02/10/2023, 8:40 PM
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

Jonny

02/10/2023, 8:42 PM
If the arcs are always 90 degrees, I believe I could find the points for the bigger arcs
k

Kirill Grouchnikov

02/10/2023, 8:43 PM
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

Jonny

02/10/2023, 8:45 PM
Alright. Well this is a lot trickier than it should be!
k

Kirill Grouchnikov

02/10/2023, 8:45 PM
I’d say it’s the usual amount of math for custom paths
j

Jonny

02/10/2023, 8:45 PM
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

romainguy

02/10/2023, 9:29 PM
Did you try the stamped path idea with a round rect?
j

Jonny

02/10/2023, 9:48 PM
@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

romainguy

02/10/2023, 9:50 PM
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

Jonny

02/10/2023, 9:52 PM
Interesting. I'm worried that it wont bend appropriately to create the desired corners however.
r

romainguy

02/10/2023, 10:00 PM
It will bend appropriately but it might be too much and distort the corners. Worth a try though
j

Jonny

02/10/2023, 10:14 PM
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

Kirill Grouchnikov

02/10/2023, 11:27 PM
Upload your images here so that they can be zoomed without going to an external site
j

Jonny

02/10/2023, 11:42 PM
There
k

Kirill Grouchnikov

02/10/2023, 11:54 PM
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

Jonny

02/11/2023, 12:41 AM
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

Kirill Grouchnikov

02/11/2023, 12:43 AM
Nice
j

Jonny

02/11/2023, 12:46 AM
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

Kirill Grouchnikov

02/11/2023, 12:51 AM
Seven more pieces to go 😃
j

Jonny

02/11/2023, 12:52 AM
I believe 5. The lines are created when the path is closed.
k

Kirill Grouchnikov

02/11/2023, 12:53 AM
Close goes from the last point to the first. It doesn't close all the jumps in the middle
j

Jonny

02/11/2023, 12:54 AM
Yes I thought so, but closing two arcs will add lines at the sides
k

Kirill Grouchnikov

02/11/2023, 12:54 AM
Wouldn't really save you much, since you need to compute the first point coordinates in any case
j

Jonny

02/11/2023, 12:55 AM
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

Kirill Grouchnikov

02/11/2023, 12:58 AM
The inners are identical. The outers are identical too.
j

Jonny

02/11/2023, 12:59 AM
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

ephemient

02/11/2023, 4:47 AM
the math isn't that bad, I think
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

Jonny

02/11/2023, 9:13 PM
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

ephemient

02/12/2023, 12:30 AM
go for it. the code's not that clean, but it should be easy enough to tweak to whatever you need.