[英]How to set an image instead of white color in this code?
我正在尝试用JAVA制作某种Paint程序。 通过图形类,我可以设置一个绘画空间并在其上进行绘制。 我希望此空间是图像而不是空白,尽管我付出了所有努力,但我不能。 如果成功,则无法绘制图像。
带有图片的无效代码: https : //pastebin.com/zNnWGjgS
Stackoverflow forces me to put some code here but it's too long
没有图像的工作代码: https : //pastebin.com/r1nFHY9c
Stackoverflow forces me to put some code here but it's too long
请帮助我。 谢谢。
只需快速查看一下paintComponent,我就会发现您很困惑。 您要做的就是将图像的Graphics2D g2
加载到Graphics2D g2
并在其上绘制线条。 在您的非工作示例中,您:
使用createImage(getSize().width, getSize().height);
创建一个新图像
您将图形g2设置为空的图像图形
您加载image
并放弃之前的初始化,而将g2留空。
您绘制图像,同时对g2图形进行所有更改。
要解决您的错误,只需将paintComponent更改为:
@Override
protected void paintComponent(Graphics g) {
if (image == null) {
try {
image = ImageIO.read(new URL("https://i.imgur.com/mjxu50B.png"));
} catch (Exception e) {
e.printStackTrace();
}
g2 = (Graphics2D) image.getGraphics();
// enable antialiasing
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLACK);
}
g.drawImage(image, 0, 0, null);
}
PS。 在以后的发布中,尝试仅发布不起作用的示例,并尝试使其尽可能简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.