Swing/Zoom のバックアップの現在との差分(No.2)
TITLE:MouseWheelで画像のズームイン・アウト表示
Posted by aterai at 2006-10-16
MouseWheelで画像のズームイン・アウト表示
- category: swing folder: Zoom title: MouseWheelで画像のズームイン・アウト表示 tags: [MouseWheelListener, ImageIcon, JComponent] author: aterai pubdate: 2006-10-16T13:11:04+09:00 description: マウスホイールなどで画像をズームイン、ズームアウトします。 image:
概要
マウスホイールなどで画像をズームイン、ズームアウトします。- &jnlp;
- &jar;
- &zip;
Screenshot
Advertisement
サンプルコード
#spanend
#spandel
class ZoomImage extends JComponent implements MouseWheelListener {
#spanend
private final ImageIcon icon;
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#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 = 1.0d;
public ZoomImage(final ImageIcon icon) {
private double scale = 1d;
protected ZoomImage(Image image) {
super();
this.icon = icon;
iw = icon.getIconWidth();
ih = icon.getIconHeight();
addMouseWheelListener(this);
this.image = image;
iw = image.getWidth(this);
ih = image.getHeight(this);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
#spanadd
#spanend
@Override public void updateUI() {
removeMouseWheelListener(handler);
super.updateUI();
handler = e -> changeScale(e.getWheelRotation());
addMouseWheelListener(handler);
}
#spanadd
#spanend
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.scale(scale, scale);
g2.drawImage(icon.getImage(), 0, 0, iw, ih, this);
g2.drawImage(image, 0, 0, iw, ih, this);
g2.dispose();
}
public void mouseWheelMoved(MouseWheelEvent e) {
changeScale(e.getWheelRotation());
}
#spanadd
#spanend
public void initScale() {
scale = 1.0d;
scale = 1d;
repaint();
}
#spanadd
#spanend
public void changeScale(int iv) {
scale = Math.max(0.05d, Math.min(5.0d, scale-iv*0.05d));
scale = Math.max(.05, Math.min(5d, scale - iv * .05));
repaint();
}
}
解説
上記のサンプルではホイールの上回転で拡大、下回転で縮小しています。解説
- 画像の拡大・縮小表示は
JPanel#paintComponent(...)
をオーバーライドしてGraphics2D#scale(...)
で設定 - 拡大・縮小率はマウスホイールの上方向回転を拡大、下方向回転を縮小として適用
コメント
- ih = icon.getIconWidth();の部分はgetIconHeight();ではありませんでしょうか? -- syo?
- ご指摘ありがとうございます。スクリーンショットもよく見たら中の画像が正方形になってますね(^^;。修正しておきます。 -- aterai