我尝试环顾四周,但不明白如何在java中绘制图形。让我举个例子。
假设我想创建一个自定义方法来填充三角形,它需要三个点作为参数。如果无法创建 Graphics 对象,如何使用 fillPolygon(int[] xPoints, int[] yPoints, int nPoints) 方法?
最佳答案
您应该了解的第一件事(也许您已经知道)是,Graphics
是您写入到的位置,而不是您写入的位置。大多数时候它是您的计算机屏幕,例如当您使用 Swing 时。
您还可以通过写入从BufferedImage.getGraphics获得的Graphics
来直接绘制到空图像。 :
Image myImage = new BufferedImage(...);
Graphics graphImage = myImage.getGraphics();
graphImage.setColor(Color.BLUE);
graphImage.fillPolygon(...); // set some blue pixels inside the BufferedImage
然后您可以将该图像转换为任何图像格式。
现在是一个愚蠢的例子,您不应该这样做(请参阅下面的真正的 Swing 过程): 您可以在 Swing 组件中绘制图像
public class MyJPanel extends Panel {
@Override
public void paintComponent(Graphics g) { // g is your screen
...
g.drawImage(myImage,...); // draw your image to the screen
...
}
}
标准的 Swing 程序是直接写入屏幕:
public class MyJPanel extends Panel {
@Override
public void paintComponent(Graphics g) { // g is your screen
...
g.fillPolygon(...); // directly writes your pixels to the screen buffer
...
}
}
(挑剔者的评论:直接写入屏幕缓冲区并不完全正确,因为 Swing 是双缓冲的。)
关于Java-如何绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7273845/