繁体   English   中英

使用Java的Graphics或Graphics2D类,如何绘制String?

[英]Using Java's Graphics or Graphics2D classes, how do I paint a String?

我有一个String ,我想把它画在图像上。 我能够绘制点和绘制线条,但是,即使在阅读了2D图形教程文本部分之后,我也无法弄清楚如何将String绘制到绘图上。

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

请查看以下方法。

g.drawString();

drawString()方法将执行您所需的操作。

使用示例:

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

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

如果你想玩你的字符串的形状 (例如:填充:红色和笔画:蓝色):

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM