Java 我应该显式地处理图形对象吗?
javadoc说: 为了提高效率,程序员应该在完成使用 仅当图形对象是直接从组件或 另一个图形对象 那么在下面的代码中,我应该在返回之前调用Java 我应该显式地处理图形对象吗?,java,swing,awt,Java,Swing,Awt,javadoc说: 为了提高效率,程序员应该在完成使用 仅当图形对象是直接从组件或 另一个图形对象 那么在下面的代码中,我应该在返回之前调用graphics.dispose()? 或者,我可以吗 { ... BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); java.awt.Graphics graphics=result.getGraphics(); g
graphics.dispose()
?
或者,我可以吗
{ ...
BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
java.awt.Graphics graphics=result.getGraphics();
graphics.drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
return result;
}
buffereImage结果将返回并在其他地方使用。因为由于JavaDocgetGpahics()
方法将转发到createGraphics()
您应该在方法末尾处理图形对象
public class Main{
public static void main(String[] args) {
BufferedImage img = get();
Graphics g = img.getGraphics();
//g.drawOval(5, 5, 5, 5); //this statement will work (you'll see the cirle)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write( img, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
Files.write(Paths.get("test2.png"), imageInByte);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static BufferedImage get(){
BufferedImage res = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
Graphics g = res.getGraphics();
g.drawRect(0, 0, 20, 20);
g.dispose();
g.drawOval(5, 5, 5, 5); //this statement won't work, you'll only see the rect
return res;
}
}
如您所见,您可以在方法中保存(并且应该)处理图形
之后不能在方法中使用图形对象,因此当运行代码时,图片中不会出现圆圈。但是如果您在方法中注释掉g.drawOval(5,5,5,5)
,但在main
-方法中注释相同的语句,您将看到一个圆圈。因此,您可以在以后使用它。可以处置图形对象,也应该处置该对象
buffereImage
的getGraphics
调用在内部委托给createGraphics
,因此没有区别。createGraphics
调用最终将委托给相应的GraphicsEnvironment
实现,其中(对于SunGraphicsEnvironment
)它将创建一个新的
SunGraphics2D
实例
最后,SunGraphics2D
的dispose
方法说明如下:
/**
* This object has no resources to dispose of per se, but the
* doc comments for the base method in java.awt.Graphics imply
* that this object will not be useable after it is disposed.
* So, we sabotage the object to prevent further use to prevent
* developers from relying on behavior that may not work on
* other, less forgiving, VMs that really need to dispose of
* resources.
*/
public void dispose() {
surfaceData = NullSurfaceData.theInstance;
invalidatePipe();
}
这也解释了为什么确实应该调用dispose
(即使在默认实现中它不是严格必需的),因为result
及其关联的图形对象(graphics
)在方法调用后超出范围,我认为是的。Java通过引用返回对象。因此,如果他处理了图形对象,他是否可以对返回的对象再次使用它?我不知道,也许有人也能回答这个问题。@Loki如果他处理了它,他就不能再使用它了。@Kayaman,所以他不应该用这种方法处理它,因为他返回了BuffereImage,may希望以后使用它。正确吗?在此方法中处理它,然后对返回的结果再次调用getGraphics()
,结果如何?