在画布的左上角绘制文本。

6
如何使用canvas.drawText在屏幕中央和左上角编写一些文本? 谢谢 (-:
2个回答

25
我不知道为什么上面的答案被标记为V,因为它根本不正确。在(0,0)处绘制文本将使其超出屏幕,因为由于某种原因,文本是从底部向上绘制的(而其他所有内容似乎都是从上到下绘制的)。
如果你想要左上角:
paint = new Paint();
paint.setColor(Color.RED);
int fontSize = 20;
paint.setTextSize(fontSize);
Typeface tf = Typeface.create("FONT_NAME", Typeface.BOLD);
paint.setTypeface(tf);
paint.setTextAlign(Align.LEFT);
canvas.drawText("your_text", 0, (0+paint.getTextSize()), paint);

2
太棒了!我在这里快疯了!感谢你抽出时间用正确的答案回答了这个问题!请点赞这个答案! - Boy
是的,重要的是要知道canvas.drawText()从底部左侧开始渲染(假设对齐值设置为左对齐),而不是通常的顶部左侧。 - Ryhan
@param y 表示正在绘制的文本基线的y坐标 - Stav Bodik

1

using the ctx.textBaseline='top' it sets the position to the top then use ctx.textAlign='start' to position it to the left. example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>My Webpage</title>
        <link rel="stylesheet" href="style.css"/>
    </head>

    <body>
        <canvas id="gameCanvas"></canvas>
        <script>
        let canvas = document.getElementById('gameCanvas');
        let ctx = canvas.getContext('2d');
        canvas.height=window.innerHeight;
        canvas.width=window.innerWidth;
        ctx.fillStyle = 'rgb(0,0,0)';
        ctx.font = "15px Arial";
        ctx.textAlign='start';
        ctx.textBaseline='top';
        ctx.fillText("Hello World", 0, 0);
        </script>  
     </body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接