1 package net.sf.openrocket.gui.components;
4 import java.awt.Graphics;
5 import java.awt.Graphics2D;
6 import java.awt.RenderingHints;
7 import java.awt.image.BufferedImage;
10 import javax.imageio.ImageIO;
11 import javax.swing.JFrame;
12 import javax.swing.JPanel;
13 import javax.swing.SwingUtilities;
15 import net.miginfocom.swing.MigLayout;
16 import net.sf.openrocket.util.MathUtil;
19 * Draws a BufferedImage centered and scaled to fit to the component.
21 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
23 public class ImageDisplayComponent extends JPanel {
25 private BufferedImage image;
27 public ImageDisplayComponent() {
31 public ImageDisplayComponent(BufferedImage image) {
37 protected void paintComponent(Graphics g) {
38 super.paintComponent(g);
44 final int width = Math.max(this.getWidth(), 1);
45 final int height = Math.max(this.getHeight(), 1);
47 final int origWidth = Math.max(image.getWidth(), 1);
48 final int origHeight = Math.max(image.getHeight(), 1);
51 // Determine scaling factor
52 double scaleX = ((double) width) / origWidth;
53 double scaleY = ((double) height) / origHeight;
55 double scale = MathUtil.min(scaleX, scaleY);
62 // Center in the middle of the component
63 int finalWidth = (int) Math.round(origWidth * scale);
64 int finalHeight = (int) Math.round(origHeight * scale);
66 int posX = (width - finalWidth) / 2;
67 int posY = (height - finalHeight) / 2;
73 int dx2 = posX + finalWidth;
74 int dy2 = posY + finalHeight;
80 Graphics2D g2 = (Graphics2D) g;
81 g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
82 g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
83 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
84 g2.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
89 public BufferedImage getImage() {
94 public void setImage(BufferedImage image) {
100 public static void main(String[] args) throws Exception {
101 final BufferedImage image = ImageIO.read(new File("test.png"));
103 SwingUtilities.invokeAndWait(new Runnable() {
107 JFrame frame = new JFrame();
109 JPanel panel = new JPanel(new MigLayout("fill"));
110 panel.setBackground(Color.red);
113 ImageDisplayComponent c = new ImageDisplayComponent(image);
114 panel.add(c, "grow");
116 frame.setSize(500, 500);
117 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
118 frame.setVisible(true);