0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Compose で、区間ごとに色を変えた横帯グラフを描く 前編

0
Posted at

はじめに

Jetpack Compose の Canvas で、1 日の予定を 1 本の横長の帯で表すグラフを、前編・後編の 2 回に分けて作ります。

使うデータ

まずは、準備から
「何分から何分まで、何をしていたか」のリストです。

data class Segment(
    val startMinute: Int, // 開始(グラフの左端からの分数)
    val endMinute: Int,   // 終了
    val type: String,     // 種類(作業・会議・休憩など)
)

val segments = listOf(
    Segment(0, 120, "作業"),
    Segment(120, 180, "会議"),
    Segment(180, 240, "休憩"),
    Segment(240, 480, "作業"),
    Segment(480, 540, "会議"),
)

よくある書き方

Canvas(modifier) {
    val width = size.width / segments.size // 個数で等分している
    segments.forEachIndexed { i, segment ->
        drawRect(
            color = Color.Gray,
            topLeft = Offset(width * i, 0f),
            size = Size(width, size.height),
        )
    }
}

帯を個数で等分しているので、1 時間の会議も 4 時間の作業も同じ幅になります。
これでは、どれにどれくらい時間を使ったのかが分かりません。

おすすめの書き方

@Composable
fun TimelineBar(segments: List<Segment>, totalMinutes: Int, modifier: Modifier = Modifier) {
    Canvas(modifier) {
        val gap = 2.dp.toPx() // 区切りのすき間
        segments.forEach { segment ->
            val left = size.width * segment.startMinute / totalMinutes
            val right = size.width * segment.endMinute / totalMinutes
            drawRect(
                color = Color.Gray,
                topLeft = Offset(left, 0f),
                size = Size((right - left - gap).coerceAtLeast(0f), size.height),
            )
        }
    }
}

// 使う側(9 時〜18 時の 540 分を 1 本の帯にする)
TimelineBar(segments, totalMinutes = 540, modifier = Modifier.fillMaxWidth().height(24.dp))

timeline_part1.png

  • 「開始が全体の何割の位置か」で左端、「終了が全体の何割の位置か」で右端を決めます
  • 右端から左端を引いた長さが幅になるので、時間が長いほど幅も広くなります
  • 幅から gap を少し引くと、となり同士の間にすき間ができて区切りが見えます
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?