スキップしてメイン コンテンツに移動

Java: Auto Resize Image Canvas (Swing)

I wrote an image canvas class which can be automatically re-size image so that it fits the window.
The code itself is pretty simple.
package com.dukesoftware.utils.swing.others;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;

public class AutoResizeImageCanvas extends JPanel{
    
    private Image img;

    public void setImage(Image img){
        this.img = img;
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        final int panelWidth = getWidth();
        final int panelHeight = getHeight();
        g.fillRect(0, 0, panelWidth, panelHeight);
        
        if(img != null){
            final int imgWidth = img.getWidth(null);
            final int imgHeight = img.getHeight(null);

            final double rW = (double)panelWidth / imgWidth;
            final double rH = (double)panelHeight / imgHeight;

            int newWidth;
            int newHeight;
            if(rW < rH){
                newWidth = panelWidth;
                newHeight = (int)(imgHeight*rW);
            }
            else{
                newWidth = (int)(imgWidth*rH);
                newHeight = panelHeight;
            }

            final int wOffset = calculateOffset(panelWidth, newWidth);
            final int hOffset = calculateOffset(panelHeight, newHeight);

            g.drawImage(img, wOffset, hOffset, newWidth, newHeight, null);
        }
    }

    private int calculateOffset(int panelSize, int newSize) {
        return newSize < panelSize ? (panelSize - newSize)/2:0;
    }
}

Here is an actual example usage.
If you resize the window, you can see the image inside it is automatically resized :).
public static void main(String[] args) throws IOException {
    final AutoResizeImageCanvas canvas = new AutoResizeImageCanvas();

    // jsut set image object
    canvas.setImage(ImageIO.read(new File("C:/temp/test.jpg")));

    // add the canvas to JFrame
    JFrame frame = new JFrame("Viewer");
    frame.getContentPane().add(canvas, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(640, 480));
    frame.pack();
    frame.setVisible(true);
}

コメント