はじめに
今回はすごくシンプルな棒グラフをJetpackComposeで作っていこうと思います
本文
今回は左と下部にのみ基準線がありますが、各RowやColumnのところにBoxで線を追加してあげることで囲むことも可能です
@Composable
fun BarChart(
data: Map<String, Float>,
maxValue: Int,
isShowHalf: Boolean
) {
val gray = HogeTheme.colors.Gray
val textMeasurer = rememberTextMeasurer()
val measurerStyle =
HogeTheme.typography.fontSize12.copy(color = HogeTheme.colors.Gray)
Column(
modifier = Modifier
.fillMaxSize()
.padding(start = 16.dp, end = 16.dp, bottom = 28.dp),
verticalArrangement = Arrangement.Top
) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.drawBehind {
val max =
textMeasurer.measure(
AnnotatedString(maxValue.toString()),
style = measurerStyle
)
drawLine(
color = gray200,
start = Offset(0f, 0f),
end = Offset(size.width - 64, 0f),
strokeWidth = 1.dp.toPx(),
cap = StrokeCap.Square
)
drawText(
max,
topLeft = Offset(size.width - 60, -24f)
)
if (isShowHalf) {
drawLine(
color = gray200,
start = Offset(0f, size.height / 2),
end = Offset(size.width - 64, size.height / 2),
strokeWidth = 1.dp.toPx(),
cap = StrokeCap.Square
)
val half = textMeasurer.measure(
AnnotatedString((maxValue / 2).toString()),
style = measurerStyle
)
drawText(
half,
topLeft = Offset(size.width - 60, size.height / 2 - 24)
)
}
val zero = textMeasurer.measure(
AnnotatedString("0"),
style = measurerStyle
)
drawText(
zero,
topLeft = Offset(size.width - 60, size.height - 24)
)
},
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.SpaceBetween
) {
// graph
data.forEach {
Box(
modifier = Modifier
.clip(RoundedCornerShape(topStart = 4.dp, topEnd = 4.dp))
.fillMaxHeight(it.value)
.background(HogeTheme.colors.red)
.weight(0.5f)
)
Spacer(modifier = Modifier.weight(0.5f))
}
}
// X-Axis Line
Box(
modifier = Modifier
.fillMaxWidth()
.padding(end = 24.dp)
.height(1.dp)
.background(HogeTheme.colors.gray)
)
// Scale X-Axis
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
data.keys.forEach {
Text(
modifier = Modifier.weight(0.5f),
text = it,
style = HogeTheme.typography.fontSize12.copy(color = HogeTheme.colors.gray),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.weight(0.5f))
}
}
}
}
最後に
今回は自分が仕事上で実装した簡易的なグラフを備忘録程度に記事に残してみました
どなたかのお役に立てれば幸いです