Java-如何绘制图形
我试着环顾四周,但不明白如何用java绘制图形。让我举个例子。
假设我想创建一个自定义方法来填充三角形,它需要三个点作为参数。如果无法创建 Graphics 对象,如何使用 fillPolygon(int[] xPoints, int[] yPoints, int nPoints) 方法?
I tried looking around, but can't understand how to draw graphics in java. Let me make an example.
Let's say I want to create a custom method to fill a triangle, and it takes three points as parameters. How can I use the metod fillPolygon(int[] xPoints, int[] yPoints, int nPoints) if I cannot create a Graphics object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该了解的第一件事(也许您已经知道)是
Graphics
是您写入到的位置,而不是您写入的位置。大多数时候它就是您的计算机屏幕,例如当您使用 Swing 时。您还可以通过写入从 BufferedImage.getGraphics:
然后您可以将该图像转换为任何图像格式。
现在是一个愚蠢的例子,您不应该这样做(请参阅下面的真正的 Swing 过程):
你可以在 Swing 组件中绘制图像
标准的 Swing 过程是直接写入屏幕:(
挑剔者的评论:直接写入屏幕缓冲区并不完全正确,因为 Swing 是双缓冲的。)
First thing you should understand (maybe you already know it) is that
Graphics
is where you write to, not where you write from. It is you computer screen most of the time, such as when you use Swing.You can also draw directly to an empty image by writing in the
Graphics
obtained from BufferedImage.getGraphics:You could then convert that image to any image format.
A stupid example now, which you should not do (see below for true Swing procedure):
you can draw your image in a Swing component
The standard Swing procedure is to write directly to the screen:
(Comment for the nitpickers: It is not quite true that you write directly to the screen buffer since Swing is double-buffered.)
你需要一个可以绘画的表面。一般来说,这可以通过创建您自己的组件(通过扩展,例如 swing 中的
JPanel
)然后覆盖其中的各种绘图更新方法来完成。要实现的主要相关项是 paintComponent 获取作为参数传入的 Graphics 对象。您通常还可以将
Graphics
对象转换为 Graphics2D,它为您提供了更丰富的绘图基元集。You need a surface to draw on. Generally this can be done by creating your own component (by extending, for example
JPanel
in swing) and then overriding the various drawing update methods there. The main relevant one to implement is paintComponent which gets a Graphics object passed in as a parameter.You can usually also cast your
Graphics
object to Graphics2D, which gives you a much richer set of drawing primitives.