简体   繁体   中英

setBackground() method is not working for Graphics2D object

I need some help with the Graphics2D class, I'm not sure why the setBackground() method doesn't work , the rendered image background simply remains white.

int width = 128, height = 32;

BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

Graphics2D ig2 = bi.createGraphics();
Font font = new Font("TimesRoman", Font.BOLD, 12);
ig2.setBackground(Color.BLACK);
ig2.setFont(font);
String message = "custom text";
FontMetrics fontMetrics = ig2.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringHeight = fontMetrics.getAscent();
ig2.setPaint(Color.red);
ig2.drawString(message, stringWidth - width/2, height / 4 + stringHeight / 6);

ImageIO.write(bi, "PNG", new File("src/output.jpeg"));

Thanks for your time fellas

You never filled the image or drew any filled shape. Setting the background color doesn't change the image, it only selects the color that will be used for the next operation that fills with the background color. It's like putting paint on your paintbrush, but never painting on the canvas. But as the docs for clearRect say, you should use setColor followed by fillRect instead.

There also seems to be a problem with the way you calculate the position to draw the string on the screen. You use stringWidth - width/2 . The width is 128. Let's say the stringWidth is 32. Then that will be 32 - 128/2, or 32 - 64, or -32. Depending on the width of the string, at least part of it will be drawn outside the buffered image. It will be clipped, and either invisible, or only partly visible.

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.

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