在 Android 的 Canvas 中绘制文本

发布于 2025-01-02 05:29:47 字数 700 浏览 2 评论 0原文

我想在画布内绘制文本(需要时自动添加新行)。这是我的示例代码:

    Bitmap src= getBitmap();
    Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas cs = new Canvas(dest);
    cs.drawBitmap(src, 0f, 0f, null);
    TextPaint tp= new TextPaint();
    tp.setTextSize(.....);
    tp. //Custom the text properties
    StaticLayout sl= new StaticLayout(text, tp, src.getWidth(), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
    sl.draw(cs);

这对于使用 "center|top" 重力绘制文本效果很好。但我需要能够制作“center|center”和“center|bottom”。 给定画布 srcsl 很容易计算 sl 必须去哪里,但是 如何更改 StaticLayout 的“起点”以便为其添加填充?

谢谢

I want to paint text inside a Canvas (auto adding the new lines when needed). Thats my sample code:

    Bitmap src= getBitmap();
    Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas cs = new Canvas(dest);
    cs.drawBitmap(src, 0f, 0f, null);
    TextPaint tp= new TextPaint();
    tp.setTextSize(.....);
    tp. //Custom the text properties
    StaticLayout sl= new StaticLayout(text, tp, src.getWidth(), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
    sl.draw(cs);

this works fine for painting the text with "center|top" gravity. But I'd need to be able to make "center|center" and "center|bottom".
Given the canvas src and sl is easy to calculate where sl must go but
how can I change the "start point" for the StaticLayout in order to add it a padding?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人哭 2025-01-09 05:29:47

您可以在“宽度”争论中为 StaticLayout/DynamicLayout 提供更多空间,
要在文本的顶部/底部添加一些填充,您可以使用“canvas.translate(x,y)”

You can give the StaticLayout/DynamicLayout some more space in the "width" arguement,
to get some padding on top/bottom of your text you can use "canvas.translate(x,y)"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文