简体   繁体   English

Java-如何绘制图形

[英]Java - how to draw Graphics

I tried looking around, but can't understand how to draw graphics in java. 我尝试环顾四周,但不明白如何在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? 如果无法创建Graphics对象,如何使用方法fillPolygon(int [] xPoints,int [] yPoints,int nPoints)?

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. 通常,这可以通过创建自己的组件(例如,扩展JPanel in swing)然后覆盖那里的各种图形更新方法来完成。 The main relevant one to implement is paintComponent which gets a Graphics object passed in as a parameter. 要实现的主要相关工具是paintComponent ,它获取作为参数传入的Graphics对象。

You can usually also cast your Graphics object to Graphics2D , which gives you a much richer set of drawing primitives. 通常,您还可以将Graphics对象转换为Graphics2D ,这将为您提供更加丰富的绘图基元集。

First thing you should understand (maybe you already know it) is that Graphics is where you write to , not where you write from. 首先,您应该了解(也许您已经知道) Graphics是您写入的位置 ,而不是您写入的位置。 It is you computer screen most of the time, such as when you use Swing. 大多数情况下是计算机屏幕,例如使用Swing时。

You can also draw directly to an empty image by writing in the Graphics obtained from BufferedImage.getGraphics : 您还可以通过写入从BufferedImage.getGraphics获得的Graphics来直接绘制为空图像:

Image myImage = new BufferedImage(...);
Graphics graphImage = myImage.getGraphics();
graphImage.setColor(Color.BLUE);
graphImage.fillPolygon(...);  // set some blue pixels inside the BufferedImage

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 现在是一个愚蠢的示例,您不应该这样做(有关真正的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
       ...
   }
}

The standard Swing procedure is to write directly 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
       ...
   }
}

(Comment for the nitpickers: It is not quite true that you write directly to the screen buffer since Swing is double-buffered.) (对nitpickers的评论:由于Swing是双缓冲的,因此直接写入屏幕缓冲区并不是完全正确。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM