はじめに
jetpack composeでサクッと簡単に点線を描く方法を紹介します。
実践
val points = ArrayList<Offset>().apply{
for (i in 50 .. 1000 step 20) {
add(Offset(100f, i.toFloat()))
}
}
Canvas(
modifier = Modifier.fillMaxSize(),
onDraw = {
drawPoints(
points = points,
pointMode = PointMode.Points,
color = Color.Black,
strokeWidth = 10f,
)
}
)
アレンジしたい場合
1. 横向きにしたい場合
add(Offset(100f, i.toFloat()))
の Offset()の引数に設定している数値を逆にすると横向きになります。
2. 間隔を狭めたいor広げたい場合
for (i in 50 .. 1000 step 20) {
の stepの後の数を小さくすると間隔が狭くなり、大きくすると広くなります。
3. 点の大きさを変えたい場合
strokeWidth = 10f,
の数を増やすと大きな点になります。
4.破線にしたい場合
drawPoints()の引数に
pathEffect = PathEffect.dashPathEffect(floatArrayOf(20f, 10f))
を追加すると破線になります。
floatArrayOfの第一引数に
for (i in 50 .. 1000 step 20) {
のstepの後ろの数よりも小さい数を入れると点同士が全て繋がってしまうので、それぞれ調整が必要。
アレンジ後の実装
val points = ArrayList<Offset>().apply{
- for (i in 50 .. 1000 step 20) {
+ for (x in 50 .. 1000 step 50) {
- add(Offset(100f, i.toFloat()))
+ add(Offset(x.toFloat(), 100f))
}
}
Canvas(
modifier = Modifier.fillMaxSize(),
onDraw = {
drawPoints(
points = points,
- pointMode = PointMode.Points,
+ pointMode = PointMode.Polygon,
color = Color.Black,
strokeWidth = 10f,
+ pathEffect = PathEffect.dashPathEffect(floatArrayOf(20f,10f))
)
}
)