Abh*_*bhi 4 android android-jetpack-compose android-jetpack-compose-canvas
我正在使用 Canvas 在 Jetpack Compose 中创建自定义可组合项。
使用时如何让文字居中drawText?
代码
@OptIn(ExperimentalTextApi::class)
@Composable
fun MyCenterTextInCanvas() {
val width: Dp = 200.dp
val height: Dp = 40.dp
val textMeasurer = rememberTextMeasurer()
Canvas(
modifier = Modifier
.background(Color.LightGray)
.wrapContentSize(
align = Alignment.Center,
)
.requiredSize(
width = width,
height = height,
),
) {
drawText(
textMeasurer = textMeasurer,
text = "Sample Text",
topLeft = Offset(
x = (width / 2).toPx(),
y = (height / 2).toPx(),
),
)
}
}
Run Code Online (Sandbox Code Playgroud)
撰写版本
jetpackComposeVersion = "1.3.0-alpha02"
用户界面
Thr*_*ian 11
您可以通过测量文本并将其放置为
@OptIn(ExperimentalTextApi::class)
@Composable
fun MyCenterTextInCanvas() {
val width: Dp = 200.dp
val height: Dp = 40.dp
val textMeasurer = rememberTextMeasurer()
val textLayoutResult: TextLayoutResult =
textMeasurer.measure(text = AnnotatedString("Sample Text"))
val textSize = textLayoutResult.size
Canvas(
modifier = Modifier
.background(Color.LightGray)
.requiredSize(
width = width,
height = height,
),
) {
val canvasWidth = size.width
val canvasHeight = size.height
drawText(
textMeasurer = textMeasurer,
text = "Sample Text",
topLeft = Offset(
(canvasWidth - textSize.width) / 2f,
(canvasHeight - textSize.height) / 2f
),
)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3291 次 |
| 最近记录: |