Jetpack Compose中使用自定义Chart

前言

Jetpack Compose 中没有好用的Chart,这里就自定义Chart,能根据项目需求自定义样式。

BarChart

带分组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import android.graphics.Paint
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.nativeCanvas
import com.xhkjedu.zxs_android.utils.extension.output
import kotlin.math.ceil

@Composable
fun ZBarChartWithGroup(
labelArr: List<String> = listOf("一星", "二星", "三星", "四星", "五星"),
groupNameArr: List<String> = listOf("做题数", "做对数"),
data: List<List<Float>> = listOf(
listOf(30f, 20f),
listOf(50f, 30f),
listOf(40f, 10f),
listOf(60f, 20f),
listOf(20f, 5f),
),
colorArr: List<Color> = listOf(
Color.Blue,
Color.Green,
Color.Yellow,
Color.Magenta,
Color.Cyan,
Color.Gray,
Color.LightGray,
Color.DarkGray,
Color.Black
),
yAxisSegments: Int = 5, // Y轴分段数量
showYLine: Boolean = true
) {
Canvas(modifier = Modifier.fillMaxSize()) {
val canvasWidth = size.width
val canvasHeight = size.height

// 边距
val padding = 40f // 增加左 padding 以容纳Y轴标签
val groupNameHeight = 20f
val innerWidth = canvasWidth - padding
val innerHeight = canvasHeight - padding * 2 - groupNameHeight
val groupWidth = (innerWidth / labelArr.size)

// 计算每个柱子的宽度
val barWidth = ((groupWidth / groupNameArr.size) * 0.8f).coerceIn(8f, 20f)

// 找到最大值用于比例计算
val maxValue = data.maxOfOrNull { it.maxOrNull() ?: 1f } ?: 1f
// 向上取整到最接近的整十数,使Y轴更美观
val roundedMax = ceil(maxValue / 10) * 10f

// 绘制坐标轴
// X轴
drawLine(
start = Offset(padding, canvasHeight - padding),
end = Offset(canvasWidth - padding, canvasHeight - padding),
color = Color.LightGray,
strokeWidth = 1f
)
if (showYLine) {
// Y轴
drawLine(
start = Offset(padding, padding),
end = Offset(padding, canvasHeight - padding),
color = Color.LightGray,
strokeWidth = 1f
)
}

//绘制group
val groupSpace = 30f
val groupRectWith = 20f
val groupNameWidth = groupNameArr.maxOf { it.length } * 16f + groupRectWith
val groupNameStartX =
(canvasWidth - groupNameWidth * groupNameArr.size - groupSpace * (groupNameArr.size - 1)) / 2f
groupNameArr.forEachIndexed { index, groupName ->
val groupNameX = groupNameStartX + index * (groupNameWidth + groupSpace)
val y = canvasHeight - 10f
val groupColor = colorArr[index]

drawRoundRect(
brush = Brush.linearGradient(
colors = listOf(groupColor.copy(0.4f), groupColor),
start = Offset.Zero,
end = Offset(0f, size.height) // 垂直
),
topLeft = Offset(groupNameX, y),
size = Size(20f, 20f),
cornerRadius = CornerRadius(4f, 4f)
)

drawContext.canvas.nativeCanvas.drawText(
groupName,
groupNameX + groupRectWith + 8f,
y + 14f,
Paint().apply {
textSize = 14f
color = android.graphics.Color.BLACK
textAlign = Paint.Align.LEFT
}
)
}


// 绘制Y轴刻度、网格线和数值
val segmentValue = roundedMax / yAxisSegments
for (i in 0..yAxisSegments) {
val value = i * segmentValue
val y = canvasHeight - padding - (value / roundedMax) * innerHeight

// 绘制网格线
drawLine(
start = Offset(padding, y),
end = Offset(canvasWidth - padding, y),
color = Color.LightGray,
strokeWidth = 1f,
alpha = 0.5f
)

// 绘制Y轴刻度值
drawContext.canvas.nativeCanvas.drawText(
value.toInt().toString(),
padding - 10,
y + 10,
Paint().apply {
textSize = 14f
color = android.graphics.Color.GRAY
textAlign = Paint.Align.RIGHT
}
)
}


val startX = padding
if (data.size == labelArr.size) {
// 绘制每个柱子和顶部数值
labelArr.forEachIndexed { labelIndex, label ->
val groupX = startX + labelIndex * groupWidth
// 绘制X轴标签
drawContext.canvas.nativeCanvas.drawText(
label,
groupX + groupWidth / 2,
canvasHeight - padding + 24,
Paint().apply {
textSize = 14f
color = android.graphics.Color.GRAY
textAlign = Paint.Align.CENTER
}
)

data.get(labelIndex).forEachIndexed { groupIndex, barValue ->
val barColor = colorArr[groupIndex]
// 计算柱子高度(按比例)
val barHeight = (barValue / roundedMax) * innerHeight
val barSpace = 10f
val barLeftSpace =
(groupWidth - barWidth * groupNameArr.size - barSpace * (groupNameArr.size - 1)) / 2
// 计算柱子位置
val barX = groupX + barLeftSpace + barSpace * groupIndex + barWidth * groupIndex
val y = canvasHeight - padding - barHeight

// 绘制柱子
drawRoundRect(
brush = Brush.linearGradient(
colors = listOf(barColor.copy(0.4f), barColor),
start = Offset.Zero,
end = Offset(0f, size.height) // 垂直
),
topLeft = Offset(barX, y),
size = Size(barWidth, barHeight),
cornerRadius = CornerRadius(barWidth / 2, barWidth / 2)
)

// 在柱顶绘制数值
drawContext.canvas.nativeCanvas.drawText(
barValue.output(),
barX + barWidth / 2,
y - 10,
Paint().apply {
textSize = 14f
color = android.graphics.Color.BLACK
textAlign = Paint.Align.CENTER
}
)
}
}
}
}
}

雷达图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import android.graphics.Paint
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.unit.dp
import kotlin.math.*

@Composable
fun ZRadarChart(
data: List<Float>,
valueLabelArr: List<String> = listOf(),
labels: List<String>,
gridLevels: Int = 5,
strokeColor: Color = Color(0xFF2196F3),
textColor: Color = Color.Gray,
labelSizeSp: Float = 12f
) {
require(labels.size == data.size) { "Labels and values must have the same size" }
require(labels.size >= 3) { "At least 3 axes are required" }
var maxValue = data.maxOrNull() ?: 1.0f
maxValue *= 1.1f
val vLabelArr = mutableListOf<String>()
if (valueLabelArr.size != data.size) {
vLabelArr.addAll(data.map { getFloatStr(it) })
} else {
vLabelArr.clear()
vLabelArr.addAll(valueLabelArr)
}

Canvas(modifier = Modifier.fillMaxSize()) {
val radius = (size.minDimension / 2f) * 0.8f
val center = Offset(size.width / 2, size.height / 2)

val axisCount = data.size
val angleStep = (2 * PI).toFloat() / axisCount

// Draw grid lines (concentric polygons)
for (level in 1..gridLevels) {
drawPolygon(
center,
radius * level / gridLevels,
axisCount,
angleStep,
color = Color.LightGray.copy(alpha = 0.3f)
)
}

drawGridLines(
center,
radius,
axisCount,
angleStep,
color = Color.LightGray.copy(alpha = 0.3f)
)

// Draw filled area
val dataPoints = getDataPoints(center, radius, data, maxValue, angleStep)

// Draw outline
drawPolygonOutline(dataPoints, strokeColor)


val labelPoints = getLabelPoints(center, radius, data, maxValue, angleStep)
for ((index, offset) in labelPoints.withIndex()) {
drawLabelCenter(offset, vLabelArr[index], textColor, 8f)
}

// Draw labels
for (i in labels.indices) {
val label = labels[i]
val angle = (i * angleStep)
var textOffset = calculateLabelPosition(center, radius, angle)

val textWidth = getTextWidth(label, labelSizeSp)
if (textOffset.x < center.x) {
textOffset -= Offset(textWidth + 26f, 0f)
} else {
textOffset += Offset(26f, 0f)
}
textOffset += Offset(0f, labelSizeSp / 2 * density)
drawLabel(textOffset, label, textColor, labelSizeSp)
}
}
}

fun getFloatStr(num: Float): String {
if (num.toInt() - num == 0f) {
return num.toInt().toString()
} else {
return num.toString()
}
}

private fun DrawScope.drawPolygon(
center: Offset,
radius: Float,
sides: Int,
angleStep: Float,
color: Color
) {
val path = androidx.compose.ui.graphics.Path().apply {
moveTo(center.x + radius * cos(-angleStep), center.y + radius * sin(-angleStep))
for (i in 0 until sides) {
lineTo(
center.x + radius * cos(i * angleStep - angleStep),
center.y + radius * sin(i * angleStep - angleStep)
)
}
close()
}
drawPath(path, color, style = Stroke(width = 1.dp.toPx()))
}

private fun DrawScope.drawGridLines(
center: Offset,
radius: Float,
sides: Int,
angleStep: Float,
color: Color
) {
val path = androidx.compose.ui.graphics.Path().apply {

for (i in 0 until sides) {
moveTo(center.x, center.y)
lineTo(
center.x + radius * cos(i * angleStep),
center.y + radius * sin(i * angleStep)
)
}
close()
}
drawPath(path, color, style = Stroke(width = 1.dp.toPx()))
}

private fun getDataPoints(
center: Offset,
radius: Float,
data: List<Float>,
maxValue: Float,
angleStep: Float
): List<Offset> {
return data.mapIndexed { index, value ->
val ratio = min(value / maxValue, 1f)
val angle = index * angleStep
center + Offset(
(ratio * radius * cos(angle)),
(ratio * radius * sin(angle))
)
}
}

private fun getLabelPoints(
center: Offset,
radius: Float,
data: List<Float>,
maxValue: Float,
angleStep: Float
): List<Offset> {
return data.mapIndexed { index, value ->
val ratio = min(value / maxValue, 1f)
val angle = index * angleStep
center + Offset(
((ratio * radius + 12f) * cos(angle)),
((ratio * radius + 12f) * sin(angle))
)
}
}

private fun DrawScope.drawPolygonOutline(
points: List<Offset>,
color: Color
) {
if (points.size < 2) return
val path = androidx.compose.ui.graphics.Path().apply {
moveTo(points[0].x, points[0].y)
points.forEach { lineTo(it.x, it.y) }
close()
}
drawPath(path, color, style = Stroke(width = 2f))
}

private fun calculateLabelPosition(center: Offset, radius: Float, angle: Float): Offset {
return center + Offset((radius) * cos(angle), (radius) * sin(angle))
}

private fun DrawScope.getTextWidth(text: String, textSizeSp: Float): Float {
val paint = android.graphics.Paint().apply {
this.textSize = textSizeSp * density // 转换为 px
typeface = android.graphics.Typeface.DEFAULT
}
return paint.measureText(text) // 返回 px 单位的宽度
}

private fun DrawScope.drawLabel(offset: Offset, label: String, color: Color, textSize: Float) {
val paint = androidx.compose.ui.graphics.Paint().asFrameworkPaint().apply {
this.color = color.toArgb()
this.textSize = textSize * density
typeface = android.graphics.Typeface.DEFAULT_BOLD
}
drawContext.canvas.nativeCanvas.drawText(label, offset.x, offset.y, paint)
}


private fun DrawScope.drawLabelCenter(
offset: Offset,
label: String,
color: Color,
textSize: Float
) {
val paint = androidx.compose.ui.graphics.Paint().asFrameworkPaint().apply {
this.color = color.toArgb()
this.textSize = textSize * density
typeface = android.graphics.Typeface.DEFAULT
textAlign = Paint.Align.CENTER
}
val fontMetrics = paint.fontMetrics
val drawY = offset.y - (fontMetrics.ascent + fontMetrics.descent) / 2
drawContext.canvas.nativeCanvas.drawText(label, offset.x, drawY, paint)
}

调用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
val data = listOf(70f, 80f, 60f, 90f, 30f, 70f, 80f)
val valueLabelArr = data.map { ZTimeUtils.formatSecondsToMinutesAndSeconds(it.toInt()) }
val labels = listOf(
"教材同步练",
"我的任务",
"学习资料",
"错题本",
"AI测评",
"知识图谱",
"知识点专练"
)

Box(
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
.padding(16.dp),
contentAlignment = androidx.compose.ui.Alignment.Center
) {
ZRadarChart(data = data, labels = labels, valueLabelArr = valueLabelArr)
}