Swing/Zoom のバックアップの現在との差分(No.1)
TITLE:MouseWheelで画像のズームイン・アウト表示
MouseWheelで画像のズームイン・アウト表示
編集者:Terai Atsuhiro~
作成日:2006-10-16
更新日:2023-12-08 (金) 17:08:03
概要
マウスホイールなどで画像をズームイン、ズームアウトします。Screenshot
Advertisement
概要
マウスホイールなどで画像をズームイン、ズームアウトします。サンプルコード
#spanend
#spanadd
class ZoomImage extends JPanel {
#spanend
private transient MouseWheelListener handler;
private final transient Image image;
private final int iw;
private final int ih;
private double scale = 1d;
protected ZoomImage(Image image) {
super();
this.image = image;
iw = image.getWidth(this);
ih = image.getHeight(this);
}
#spandel
#screenshot
#spanend
@Override public void updateUI() {
removeMouseWheelListener(handler);
super.updateUI();
handler = e -> changeScale(e.getWheelRotation());
addMouseWheelListener(handler);
}
#spandel
**サンプルコード [#n33b6ada]
#spanend
#spandel
#code{{
#spanend
class ZoomImage extends JComponent implements MouseWheelListener {
private final ImageIcon icon;
private final int iw;
private final int ih;
private double scale = 1.0d;
public ZoomImage(final ImageIcon icon) {
super();
this.icon = icon;
iw = icon.getIconWidth();
ih = icon.getIconWidth();
addMouseWheelListener(this);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.scale(scale, scale);
g2.drawImage(icon.getImage(), 0, 0, iw, ih, this);
}
public void mouseWheelMoved(MouseWheelEvent e) {
changeScale(e.getWheelRotation());
}
public void initScale() {
scale = 1.0d;
repaint();
}
public void changeScale(int iv) {
scale = Math.max(0.05d, Math.min(5.0d, scale-iv*0.05d));
repaint();
}
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.scale(scale, scale);
g2.drawImage(image, 0, 0, iw, ih, this);
g2.dispose();
}
#spanadd
#spanend
public void initScale() {
scale = 1d;
repaint();
}
#spanadd
#spanend
public void changeScale(int iv) {
scale = Math.max(.05, Math.min(5d, scale - iv * .05));
repaint();
}
#spanadd
}
#spanend
View in GitHub: Java, Kotlin- &jnlp;
- &jar;
- &zip;
解説
上記のサンプルではホイールの上回転で拡大、下回転で縮小しています。解説
- 画像の拡大・縮小表示は
JPanel#paintComponent(...)
をオーバーライドしてGraphics2D#scale(...)
で設定 - 拡大・縮小率はマウスホイールの上方向回転を拡大、下方向回転を縮小として適用