简体   繁体   中英

does java bufferedImage really give a black canvas?

I was trying to achieve the same thing with two different approaches. I want to draw a simple rectangle.

In the first approach, I simple get g object and draw directly on it.

public void paintComponent(Graphics g){ 
    super.paintComponent(g);
    g.drawRect(100, 100, 50, 50);
}

In the second approach, i get a image canvas draw on it and then draw the image on the graphics object of jpanel.

public void paintComponent(Graphics g){
    super.paintComponent(g);
    BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    Graphics a = img.getGraphics();
    a.drawRect(100, 100, 50, 50);       
    g.drawImage(img, 0, 0, 500, 500, null);
}

I was hoping both would result in similar output but the one below where i am drawing an image gives white rectangle on black background while the one on the top gives black rectangle on a white background. Why is this so?

When you do custom painting on a component. The background is painted first. It appears you are extending JComponent which will simply paint a white background. Other Swing components will use the color specified by the setBackground() method, for example a JPanel defaults to the grey color. The graphics object is then set to be the foreground color of the component so you can do your custom painting. The default foreground color is black.

When you create a BufferedImage it looks like it is filled in with a black background by default and then the color of the Graphics object is set to WHITE so you can do custom painting and it will show up on the black background. You can always fill the background of the buffered image to be any color and then change the graphics object to use any color for the foreground.

You are using TYPE_INT_RGB. You can explore the other types at this link . TYPE_INT_ARGB supports a transparent background, which is what you may be looking for.

But it is not as simple as setting the type. The background color is also affected by the component type when you embed it, or by the file format when you save it as a file. PNG, for example, is a file format that supports transparency. You will have to experiment with different component types to see whether they affect transparency or not.

You don't call setColor() , so the rectangle is drawn with the default colour. The default colours are different in the two examples, which is why you should always set the colour explicitly (and fill the background with your background colour).

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