钟表效果图:

1.画外圆圈

drawCircle(color = textColor,

2.画小时刻度

获得刻度最外侧与圆心的距离

val lineOuterR = (size.minDimension / 2.0f).minus(6.dp.toPx())

获得刻度最内侧与圆心的距离

val lineInnerR = (size.minDimension / 2.0f).minus(18.dp.toPx())

循环12次,画12个刻度

for (i in 0..11) { val xRad = cos(30.0 * i * Math.PI / 180F) val yRad = sin(30.0 * i * Math.PI / 180F) drawLine( color = textColor, start = Offset( (center.x + (lineInnerR * xRad)).toFloat(), (center.y + (lineInnerR * yRad)).toFloat() ), end = Offset( (center.x + (lineOuterR * xRad)).toFloat(), (center.y + (lineOuterR * yRad)).toFloat() ), strokeWidth = 2.dp.toPx(), cap = StrokeCap.Round, )}

3.画内圆圈

// 内圆圈val rInnerCircle = (size.minDimension / 2.0f).minus(22.dp.toPx())drawCircle(color = textColor, radius = rInnerCircle,

4.中心小圆点

drawCircle(color = textColor, radius = 4.dp.toPx())

5.时针

val xRadHour = cos(hourAngle * Math.PI / 180F)val yRadHour = sin(hourAngle * Math.PI / 180F)val rHour = rInnerCircle.times(3).div(4)drawLine( color = hourHandColor, start = Offset(center.x, center.y), end = Offset( (center.x + (rHour * xRadHour)).toFloat(), (center.y + (rHour * yRadHour)).toFloat() ), strokeWidth = 3.dp.toPx(), cap = StrokeCap.Round)

6.分针

val xRadMinute = cos(minuteAngle * Math.PI / 180F)val yRadMinute = sin(minuteAngle * Math.PI / 180F)val rMinute = rInnerCircle.minus(2.dp.toPx())drawLine( color = minuteHandColor, start = Offset(center.x, center.y), end = Offset( (center.x + (rMinute * xRadMinute)).toFloat(), (center.y + (rMinute * yRadMinute)).toFloat() ), strokeWidth = 2.dp.toPx(), cap = StrokeCap.Round)

7.秒针

val xRadSecond = cos(secondAngle * Math.PI / 180F)val yRadSecond = sin(secondAngle * Math.PI / 180F)val rSecond = lineOuterR.minus(2.dp.toPx())drawLine( color = secondHandColor, start = Offset(center.x, center.y), end = Offset( (center.x + (rSecond * xRadSecond)).toFloat(), (center.y + (rSecond * yRadSecond)).toFloat() ), strokeWidth = 1.dp.toPx(), cap = StrokeCap.Round)

整体代码

fun ClockView( hourAngle: Float, minuteAngle: Float, secondAngle: Float, modifier: Modifier = Modifier, textColor: Color = MaterialTheme.colors.onSurface, hourHandColor: Color = MaterialTheme.colors.onSurface, minuteHandColor: Color = MaterialTheme.colors.onSurface, secondHandColor: Color = MaterialTheme.colors.onSurface) { Canvas(modifier = modifier) { //外圆圈 drawCircle(color = textColor,

使用时传入时、分、秒的角度就可以了

ClockView(0f, 100f, 270f)