gpt4 book ai didi

java - Buttom "Save"保存空白 Canvas

转载 作者:太空宇宙 更新时间:2023-11-04 14:50:01 26 4
gpt4 key购买 nike

这是我的简单图形编辑器的部分代码。这应该保存我绘制的图像,但它保存的是空白 Canvas 。我做错了什么?

BufferedImage bi = new BufferedImage(center.getWidth(), center.getHeight(), BufferedImage.TYPE_INT_RGB);  
Graphics2D g2 = bi.createGraphics();
center.printAll(g2);
g2.dispose();
JFileChooser jfc = new JFileChooser();
int ret = jfc.showDialog(null, "Save file");
if (ret == JFileChooser.APPROVE_OPTION) {
File outputFile = jfc.getSelectedFile();
ImageIO.write(bi, "BMP", outputFile);

最佳答案

双缓冲在绘制组件和不可显示的组件(不属于可见框架的一部分)时必须暂时禁用需要首先布局(否则它们的大小为0x0)。

以下代码将任何组件绘制到 BufferedImage 中:

public static BufferedImage paint(Component component) {
RepaintManager repaintManager = RepaintManager.currentManager(component);
boolean wasDoubleBuffered = repaintManager.isDoubleBufferingEnabled();
try {
repaintManager.setDoubleBufferingEnabled(false);
Dimension size = component.getSize();
if (!component.isDisplayable()) {
if (size.width <= 0 || size.height <= 0) {
size = component.getPreferredSize();
component.setSize(component.getPreferredSize());
}
synchronized (component.getTreeLock()) {
layoutComponent(component);
}
}

BufferedImage image = createCompatibleImage(size.width, size.height);
Graphics2D g2 = image.createGraphics();
component.paint(g2);
g2.dispose();
return image;
}
finally {
repaintManager.setDoubleBufferingEnabled(wasDoubleBuffered);
}
}

private static void layoutComponent(Component component) {
component.doLayout();
if (component instanceof Container) {
for (Component child : ((Container) component).getComponents()) {
layoutComponent(child);
}
}
}

public static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}

public static BufferedImage createCompatibleImage(int width, int height) {
return getGraphicsConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}

关于java - Buttom "Save"保存空白 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23911771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com