2011-04-29 68 views
0

我有一個動畫,並希望當它到達顯示區域的左側時逐漸消失。擺動動畫

AffineTransform at = new AffineTransform(); 
at.scale(-1, 1); 
at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1); 
if ((clip.x - clip.width) < (at.getTranslateX() - bufImg.getWidth())) { 
    g2d.drawImage(bufImg, at, null); 
} else { 
at = new AffineTransform(); 
        at.scale(-1, 1); 
        at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1); 
        g2d.drawImage(bufImg, (int)at.getTranslateX(), clip.y - 1, (int)(bufImg.getWidth() - (xPositionToPixel(imgX) + bufImg.getWidth())), clip.height, null); 
} 

我從右向左繪製動畫,這就是爲什麼我縮放和翻譯每個座標的原因。 clip.x是顯示區域的開始,imgX是新的x座標。

感謝您的幫助。

我想實現我想要什麼的幾個方式,最近的是這樣的:

AffineTransform at = new AffineTransform(); 
at.scale(-1, 1); 
at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1); 

if ((clip.x - clip.width) < (at.getTranslateX() - bufImg.getWidth())) { 
    g2d.drawImage(bufImg, at, null); 
} else { 
at = new AffineTransform(); 
        at.scale(-1, 1); 
        at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1); 
        g2d.drawImage(bufImg, (int)at.getTranslateX(), clip.y - 1, (int)(bufImg.getWidth() - (xPositionToPixel(imgX) + bufImg.getWidth())), clip.height, null); 
} 

但仍然不是一個好soluation有我只是在我的萎縮圖像的寬度,但是仍然繪製完全。

+0

好,謝謝,我會改進的是,大多數的答案是非常有價值的。 – wotan2009 2011-04-29 08:55:17

回答

2

還是不知道到底是什麼問題(動畫或變換?),這裏有一個簡單的代碼片段一起玩:

final JButton button = new JButton("Swinging!"); 
    button.setSize(button.getPreferredSize()); 
    button.doLayout(); 
    final BufferedImage image = new BufferedImage(
      button.getWidth(), button.getHeight(), BufferedImage.TYPE_INT_RGB); 
    Graphics2D g = image.createGraphics(); 
    button.paint(g); 
    g.dispose(); 
    final Point location = new Point(500, 100); 
    final JPanel panel = new JPanel() { 
     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D gd = (Graphics2D) g.create(); 
      gd.translate(location.x, location.y); 
      gd.scale(-1, 1); 
      gd.drawImage(image, 0, 0, this); 
      gd.dispose(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(button.getWidth()* 10, button.getHeight() * 20); 
     } 


    }; 
    ActionListener l = new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      location.x -= 5; 
      panel.repaint(); 
      if (location.x < - button.getWidth()) { 
       ((Timer) e.getSource()).stop(); 
      } 
     } 
    }; 
    new Timer(100, l).start(); 
+0

我還沒有試過你的代碼,但是我會試着重新解釋我的問題,因爲你說你不明白它。 – wotan2009 2011-04-29 11:03:34

+0

我試過了你的代碼,這是我想要實現的,但是我的JComponent中的顯示區域比JComponent的尺寸小。我有一個裁剪區域比我的JComponent寬度和高度小20px。因此,就我而言,當我到達顯示區域的最左側時,我無法繪製整個圖像。我必須根據新位置縮小圖像的大小。這是我的難處。我希望我更清楚。 – wotan2009 2011-04-29 11:24:33

+1

@ wotan2009:這是一個有趣的片段。 – trashgod 2011-04-29 21:24:10