Using Java Graphics or Graphics2D classes, how to draw a string?

I have String, and I want to draw it on the image. However, I can draw points and draw lines, even after reading the Text part of the 2D Graphics tutorial , I cannot understand how I can take Stringand draw it in my drawing.

If I don't study the wrong tutorial (but this is the one I get whenever I look for something about Java and drawing strings using Graphicsor Graphics2D), I'm still at a dead end.

+3
source share
2 answers

Check out the following method.

g.drawString();

drawString() , .

:

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

, String.

+8

(: 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);
+3

Source: https://habr.com/ru/post/1713941/


All Articles