You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Jetpack Compose nativeCanvas绘制的路径文本设置自定义字体

Compose 原生Canvas路径文字自定义字体设置方案

直接上可运行的完整实现代码:

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.Path
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.res.ResourcesCompat
import android.graphics.Paint
import android.graphics.Typeface

@Composable
fun CustomPathText() {
    // 提前在可组合项层级加载字体,不要放到绘制回调中重复执行
    val context = LocalContext.current
    // 替换为你res/fonts目录下对应字体的资源ID,比如字体文件为custom_font.ttf则对应R.font.custom_font
    val customTypeface: Typeface? = ResourcesCompat.getFont(context, R.font.custom_font)
    
    // 自定义绘制路径示例:二阶贝塞尔曲线
    val targetPath = Path().apply {
        moveTo(80f, 400f)
        quadTo(350f, 150f, 700f, 400f)
    }

    Canvas(modifier = Modifier.fillMaxSize()) {
        drawIntoCanvas { composeCanvas ->
            composeCanvas.nativeCanvas.drawTextOnPath(
                "沿路径绘制的自定义字体文字",
                targetPath.asAndroidPath(), // Compose Path转原生Android Path
                0f, // 文字沿路径的起始偏移量
                15f, // 文字距离路径的垂直偏移量,可自行调整
                Paint().apply {
                    textSize = 56f
                    color = android.graphics.Color.BLACK
                    isAntiAlias = true // 开启抗锯齿提升文字清晰度
                    // 应用加载好的自定义字体
                    typeface = customTypeface ?: Typeface.DEFAULT // 加载失败时用系统默认字体兜底
                }
            )
        }
    }
}

注意事项

  • 不要在drawIntoCanvas的lambda内部加载字体,该回调会随视图重绘频繁执行,重复加载字体会产生不必要的性能损耗。
  • 如需调整字体样式(加粗、斜体等),可通过Typeface.create(customTypeface, Typeface.BOLD_ITALIC)等重载方法生成对应样式的Typeface再赋值。
  • 需确保模块依赖包含androidx.core:core-ktx,这是Compose项目的默认依赖,一般无需额外引入。

内容的提问来源于stack exchange,提问作者Richard Onslow Roper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:54:01