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
Last updated at Posted at 2026-11-03

はじめに

Jetpack Compose の Canvas で、1 日の予定を帯グラフにする記事の後編です。

  • 前編:それぞれの時間を、長さどおりの幅で帯に並べる(前編の記事)
  • 後編(この記事):種類ごとに色を分けて完成させる

データと帯の描き方は前編と同じです。

よくある書き方

drawRect(
    color = when (segment.type) {
        "作業" -> Color(0xFF42A5F5)
        "会議" -> Color(0xFFFFA726)
        else -> Color(0xFF66BB6A)
    },
    // ...
)

帯を描く場所で、直接色を決めています。

この書き方だと、色の説明(凡例)を作るときに、同じ色をもう一度書くことになります。片方だけ色を変えると、帯と説明の色が合わなくなります。

おすすめの書き方

// 種類と色の対応表(ここだけで色を決める)
val typeColors = mapOf(
    "作業" to Color(0xFF42A5F5),
    "会議" to Color(0xFFFFA726),
    "休憩" to Color(0xFF66BB6A),
)

帯は、前編のコードの Color.Gray を、対応表から取った色に変えるだけです。

drawRect(
    color = typeColors[segment.type] ?: Color.Gray, // 表にない種類は灰色
    topLeft = Offset(left, 0f),
    size = Size((right - left - gap).coerceAtLeast(0f), size.height),
)

**色の説明(凡例)**も、同じ対応表から作ります。

@Composable
fun Legend(colors: Map<String, Color>) {
    Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
        colors.forEach { (type, color) ->
            Row(verticalAlignment = Alignment.CenterVertically) {
                Box(Modifier.size(12.dp).background(color))
                Spacer(Modifier.width(4.dp))
                Text(type, fontSize = 13.sp)
            }
        }
    }
}

// 使う側
Legend(typeColors)
  • 色は対応表の 1 か所だけで決めるので、帯と説明の色が必ずそろいます
  • 種類を増やしたいときも、対応表に 1 行足すだけで、帯と説明の両方に反映されます

補足

  • ?: Color.Gray は、対応表にない種類が来たときに灰色で描くためのものです。色がなくても帯が消えずに済みます
  • 画像の帯の下にある時刻は、Row に Text を並べて表示しています

まとめ

  • 種類と色の対応表(Map)を 1 つ作り、帯と色の説明の両方でそれを使う
  • 表にない種類に備えて、?: で予備の色を決めておく

timeline_part2_complete.png

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?