简体   繁体   English

Java Swing:使用图像调整JPanel的大小

[英]Java Swing: Resizing JPanel with Image

I'm attempting to resize an Image I've drawn onto an ImagePanel (extending a JPanel) and it doesn't seem to be working. 我正在尝试调整已绘制到ImagePanel上的Image的大小(扩展了JPanel),但似乎无法正常工作。 I've gotten some sample code from off the internet that overrides the components paint() method, I'm thinking this might be the problem, here's my code. 我从互联网上获得了一些覆盖组件paint()方法的示例代码,我认为这可能是问题所在,这是我的代码。

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (img != null) { // Scale it by width int scaledWidth = (int)((img.getWidth() * getHeight()/img.getHeight()));
        // If the image is not off the screen horizontally...
        if (scaledWidth < getWidth()) {
            // Center the left and right destination x coordinates.

            int leftOffset = getWidth() / 2 - scaledWidth / 2;
            int rightOffset = getWidth() / 2 + scaledWidth / 2;
            g.drawImage(img, leftOffset, 0, rightOffset, getHeight(), 0, 0, img.getWidth(), img.getHeight(), null);
        }
        // Otherwise, the image width is too much, even scaled
        // So we need to center it the other direction
        else {
            int scaledHeight = (img.getHeight() * getWidth()) / img.getWidth();

            int topOffset = getHeight() / 2 - scaledHeight / 2;
            int bottomOffset = getHeight() / 2 + scaledHeight / 2;

            g.drawImage(img, 0, topOffset, getWidth(), bottomOffset, 0, 0, img.getWidth(), img.getHeight(), null);
        }
    }
}

and I'm calling it from... 我从...开始称呼它

public void resetImage(double width, double height) {
     BufferedImage scaledImage = new BufferedImage((int)width, (int)height,BufferedImage.TYPE_INT_ARGB);
     // Paint scaled version of image to new image
     Graphics2D graphics2D = scaledImage.createGraphics(); 
     graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); 

     this.setSize((int)img.getWidth(), (int)img.getHeight());
     graphics2D.drawImage(this.img, 0, 0, (int)width, (int)height, null); graphics2D.dispose(); 
}

(where width and height in this blurp are the new width and height to be applied. (其中,此Blur中的width和height是要应用的新宽度和高度。

Thanks. 谢谢。

Are you sure that method paintComponent is called? 您确定调用了paintComponent方法吗? try to call ImagePanel.repaint() in the end of resetImage 尝试调用ImagePanel.repaint()在结束resetImage

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

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