缩放并绘制BufferedImage

时间:2018-07-02 09:44:04

标签: java swing bufferedimage

我在JPanel方法上有一个带有@Override的自定义paintComponent,该方法从成员变量中提取BufferedImage并将其绘制出来。在我尝试缩放图像之前,它工作正常。从阅读中我了解到,有两种不同的方法。一种是使用Image.getScaledInstance,另一种是使用缩放图像的尺寸创建一个Graphics2D。但是,当我尝试使用这两种方法时,要么得到一个完全白色的矩形,要么什么都没有。我不确定自己在做什么错。覆盖方法的代码如下。任何意见,将不胜感激。我敢肯定这是微不足道的,但我看不到问题。

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (img != null) {
        int imageWidth = img.getWidth();
        int imageHeight = img.getHeight();
        int panelWidth = getWidth();
        int panelHeight = getHeight();

        if(imageWidth > panelWidth || imageHeight > panelHeight){
            double aspectRatio = (double)imageWidth / (double)imageHeight;
            int newWidth, newHeight;

            // rescale the height then change the width to pre
            if(imageWidth > panelWidth){
                double widthScaleFactor = (double)panelWidth / (double)imageWidth;
                newWidth = (int)(widthScaleFactor * imageWidth);
                newHeight = (int)(widthScaleFactor * imageWidth / aspectRatio);
            }else{
                double heightScaleFactor = (double)panelHeight / (double)imageHeight;
                newHeight = (int)(heightScaleFactor * imageHeight);
                newWidth = (int)(heightScaleFactor * imageHeight * aspectRatio);
            }

            //BufferedImage scaledImage = (BufferedImage)img.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_DEFAULT);
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, img.getType());
            int x = (panelWidth - newWidth) / 2;
            int y = (panelHeight - newHeight) / 2;

            //Graphics2D g2d = (Graphics2D) g.create();
            Graphics2D g2d = scaledImage.createGraphics();
            //g2d.drawImage(scaledImage, x, y, this);
            g2d.drawImage(img, 0, 0, newWidth, newHeight, null);
            g2d.dispose();
        }else{
            int x = (getWidth() - img.getWidth()) / 2;
            int y = (getHeight() - img.getHeight()) / 2;

            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawImage(img, x, y, this);
            g2d.dispose();
        }
    } 

1 个答案:

答案 0 :(得分:2)

不确定是否有帮助,因为您尚未发布SSCCE,但这可能比您的代码更好。

Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
int x = (panelWidth - newWidth) / 2;
int y = (panelHeight - newHeight) / 2;
g.drawImage(scaledImage, x, y, this);