[英]Resize and Redraw a image in a JPanel
I'm creating a simple java program to load a image and zoom in/out the image. 我正在创建一个简单的Java程序来加载图像并放大/缩小图像。 So far I have been able load the picture and zoom it. 到目前为止,我已经能够加载图片并进行缩放。 But when drawing the zoomed out image I can still see the previous image on the JPanel. 但是当绘制缩小的图像时,我仍然可以在JPanel上看到先前的图像。
Code for loading the image 加载图像的代码
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Images(jpg,png,gif)", "jpg","png","gif"));
int opt = fileChooser.showOpenDialog(this);
if(opt == JFileChooser.APPROVE_OPTION){
String filePath = fileChooser.getSelectedFile().getAbsolutePath();
try {
bufImage = ImageIO.read(fileChooser.getSelectedFile());
} catch (IOException ex) {
Logger.getLogger(ImageZoom.class.getName()).log(Level.SEVERE, null, ex);
}
image = new ImageIcon(filePath);
imgWidth = image.getIconWidth();
imgHeight = image.getIconHeight();
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, image.getIconWidth(), image.getIconHeight(), imagePanel);
}
Code for zooming in 放大代码
double scale_factor = 1.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);
Code for zooming out 缩小代码
double scale_factor = 0.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);
Can some one please suggest a way to only have the resized image on the panel? 有人可以建议一种仅在面板上显示调整大小的图像的方法吗?
This is how zooming out looks like. 这就是缩小的样子。 same problem occurs when opening a new picture. 打开新图片时也会发生相同的问题。
I tried repainting the panel but then everything vanishes. 我尝试重新粉刷面板,但随后一切都消失了。
That's because imagePanel.getGraphics()
isn't how custom painting works in Swing. 那是因为imagePanel.getGraphics()
并不是Swing中自定义绘画的工作方式。 Instead, create a custom class which extends from something like JPanel
and override it's paintComponent
method, painting your scaled image there (making sure to call super.paintComponent
first) 相反,创建一个自定义类,该类super.paintComponent
自JPanel
类,并覆盖它的paintComponent
方法,在那里绘制缩放后的图像(确保首先调用super.paintComponent
)。
See Painting in AWT and Swing and Performing Custom Painting for more details 有关更多详细信息,请参见“ AWT中的绘画”和“摇摆和执行自定义绘画 ”
For example: 例如:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.