I have a String
and I want to paint it onto an image. I am able to paint points and draw lines, however, even after reading the Text part of the 2D Graphics tutorial , I can't figure out how I can take a String
and paint it onto my drawing.
Unless I'm looking at the wrong tutorial (but it's the one I get whenever I search for anything about Java and painting Strings using Graphics
or Graphics2D
), I'm still stumped.
Check out the following method.
g.drawString();
The drawString()
method will do what you need.
An example use:
protected void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.drawString(5, 40, "Hello World!");
}
Just remember, the coordinates are regarding the bottom left of the String
you are drawing.
if you want to play with the shape of your string (eg: fill:red and 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.