JetpackComposeでアナログ時計の作成
drawCanvasのシンプルなお題としてアナログ時計の作成に取り組みました。
@Composable fun Clock() { val hour = LocalTime.now().hour val minute = LocalTime.now().minute val shortDegree = minute * 6f val longDegree = (hour % 12 + minute / 60) * 30f Column { Canvas(modifier = Modifier.fillMaxSize()) { drawCircle(Color.Gray) rotate(longDegree) { val longEnd = this.center + Offset(0f, -size.minDimension / 3) drawLine(Color.Cyan, start = this.center, end = longEnd, strokeWidth = 10f) } rotate(shortDegree) { val shortEnd = this.center + Offset(0f, -size.minDimension / 2) drawLine(Color.Yellow, start = this.center, end = shortEnd, strokeWidth = 5f) } } } }
CanvasによるdrawScopeではrotateメソッドが使えて描画するパーツを回転させられます。 以下に示すのはrotateの定義で時計のコードには現れていませんが回転の中心を変更することもできます。
inline fun DrawScope.rotate( degrees: Float, pivot: Offset = center, block: DrawScope.() -> Unit ) = withTransform({ rotate(degrees, pivot) }, block)