我有 String ,我想将它绘制到图像上。然而,即使在阅读了 2D图形教程的文本部分,我无法弄清楚如何将 String 绘制到我的绘图上。

除非我正在查看错误的教程(但是每当我搜索有关Java的任何内容并使用 Graphics Graphics2D 绘制字符串时,我都会得到),我还是难过。

有帮助吗?

解决方案

查看以下方法。

g.drawString();

drawString() 方法将满足您的需求。

使用示例:

protected void paintComponent(Graphics g){
    g.setColor(Color.BLACK);
    g.drawString(5, 40, "Hello World!");
}

请记住,坐标是关于你正在绘制的 String 的左下角。

其他提示

如果您想使用字符串的形状(例如:fill:red和stroke:blue):

Graphics2D yourGraphicsContext=(...);
Font f= new Font("Dialog",Font.PLAIN,14);
FontRenderContext frc = yourGraphicsContext.getFontRenderContext();
TextLayout tl = new TextLayout(e.getTextContent(), f, frc);
Shape shape= tl.getOutline(null);

//here, you can move your shape with AffineTransform (...)

yourGraphicsContext.setColor(Color.RED);
yourGraphicsContext.fill(shape);
yourGraphicsContext.setColor(Color.BLUE);
yourGraphicsContext.draw(shape);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top