我知道一个是创建 Graphics2D对象,一个是获取一个 Graphics2D对象。
那两个有什么区别?
我看代码里都有
public void init(){
int width=480,hight=720;
image = new BufferedImage(width,hight,BufferedImage.TYPE_INT_RGB);
//获取图形上下文
graphics = (Graphics2D)image.getGraphics();
}
(1):创建一个Graphics2D,可以画到BufferedImage中。
BufferedImage buf=new
BufferedImage(img.getWidth(this),img.getHeight(this),BufferedImage.TYPE_INT_ARGB);创建一个临时Graphics2D对象。
Graphics tmpG=buf.createGraphics();
将图像画入临时缓冲中:
tmpG.drawImage(img,10,10,this);
、
看起来都是初始化阶段使用的,之间也没什么区别麻
谢谢。
在Java中,BufferedImage
和createGraphics()
是两种用于绘制图像的类,它们在以下情况下使用:
BufferedImage
:
作为绘图对象:
当你创建一个BufferedImage
对象时,你首先创建了一个Graphics2D
对象,这是Java图像处理库中的一个对象,用于在二维图形上进行绘图操作。BufferedImage
对象提供了以下方法用于绘制图像:
- `getGraphics()`:返回当前的`Graphics2D`对象,你可以通过调用`Graphics2D.getInstance()`方法来获取它,如以下示例:
```java
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.getGraphics();
// 绘制图像
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
```
- `createGraphics()`:创建一个新的`Graphics2D`对象,可以用于在`BufferedImage`上绘制新的图像。`createGraphics()`方法接受一些参数,如`src`(可选),表示要绘制的图像的源,`width`和`height`(可选)表示图像的宽度和高度,`format`(可选)表示图像的格式(例如,`RGB`,`BGR`等),`alpha`(可选)表示透明度,`paint`(可选)表示在绘图上下文中调用的绘图方法(例如,`drawImage`,`fillRect`等)。
- 使用`createGraphics()`方法的示例:
```java
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = image.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
```
createGraphics()
:
在创建BufferedImage
对象时使用:
在创建BufferedImage
对象时,如果你不提供getGraphics()
方法的参数,createGraphics()
方法将创建一个新的Graphics2D
对象,该对象将被存储在BufferedImage
对象的Graphics
属性中。例如:
```java
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
// 将当前的`Graphics`属性设置为新创建的`Graphics2D`对象
image.setGraphics(g);
```
BufferedImage
对象的getGraphics()
方法中使用:在BufferedImage
对象的getGraphics()
方法中,你可以在一个图形上下文中使用Graphics
属性,如以下示例:
```java
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = image.getGraphics();
// 绘制图像
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
image.setGraphics(g);
// 在另一个图形上下文中使用`Graphics`属性
g = image.getGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
```
注意,getGraphics()
方法和createGraphics()
方法在创建BufferedImage
对象时是默认开启的,即创建一个既保留了当前Graphics
属性,也保存了新创建的Graphics2D
对象的图形。如果你在绘制图像后想获取当前的Graphics
属性,你可以调用getGraphics()
方法;如果你想创建一个新的Graphics2D
对象,并在图形上下文中使用它,你可以调用createGraphics()
方法。