java Graphics2D:在白色上画黑?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/575706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Graphics2D: Drawing black on white?
提问by Germán
I'm sure this is a very stupid question but I can't find the answer, I'm not experienced with the Java2D API. I'm trying to create an image and write it to GIF or PNG, and I want it to use a black pen on a white background. If I don't set any colors, I get white on black. If I use setPaint() (intended for subsequent draw operations) I get the whole canvas repainted with that color. The following sample renders the whole thing black.
我确定这是一个非常愚蠢的问题,但我找不到答案,我对 Java2D API 没有经验。我正在尝试创建一个图像并将其写入 GIF 或 PNG,我希望它在白色背景上使用黑色钢笔。如果我不设置任何颜色,我会在黑色上得到白色。如果我使用 setPaint() (用于后续绘制操作),我会用该颜色重新绘制整个画布。以下示例将整个内容呈现为黑色。
The sample is in Scala but you get the idea. Feel free to answer in Java!
该示例在 Scala 中,但您明白了。随时用Java回答!
val bi = new BufferedImage(200, 400, BufferedImage.TYPE_BYTE_BINARY )
val g = bi.createGraphics
g.setBackground(Color.WHITE)
g.setPaint(Color.BLACK)
g.draw(new Rectangle(10, 10, 30, 20))
回答by McDowell
The setBackgroundmethod is/was only for use with the clearRectmethod.
该的setBackground方法是在/只与使用clearRect方法。
Fill the rectangle with the background colour before painting:
在绘制之前用背景颜色填充矩形:
int width = 200;
int height = 400;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_BYTE_BINARY);
Graphics g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
//ready for drawing

