【问题标题】:Java Swing: Resizing JPanel with ImageJava Swing:使用图像调整 JPanel 的大小
【发布时间】:2011-01-13 21:15:14
【问题描述】:

我正在尝试调整已绘制到 ImagePanel(扩展 JPanel)上的图像大小,但它似乎不起作用。我从互联网上获得了一些覆盖组件 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);
        }
    }
}

我从...调用它

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(); 
}

(此模糊中的宽度和高度是要应用的新宽度和高度。

谢谢。

【问题讨论】:

  • 什么不起作用?你期望会发生什么?为我们提供更多帮助 - 我们不会为了帮助您而重建您的环境。

标签: java image user-interface swing resize


【解决方案1】:

你确定调用了paintComponent 方法吗?尝试在resetImage 末尾调用ImagePanel.repaint()

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多