我试图用java swing来产生翻转效果,但是我的翻转方法看起来并不像一个真正的flip.In --我的方法--用x变量和x速度改变宽度,使图像变小,然后检查x是否是图像的一半的>=。希望有人能帮我改进一下,谢谢。
动画类
public class Animation extends JPanel implements MouseListener {
private static final long serialVersionUID = 3264508834913061718L;
public Timer timer;
public int x = 0;
public int xspeed = 2;
public boolean turning = true;
public String pic = "/images/image.jpg";
public URL url = this.getClass().getResource(pic);
public ImageIcon im = new ImageIcon(url);
public String rev = "/images/image2.jpg";
public URL url2 = this.getClass().getResource(rev);
public ImageIcon reverse = new ImageIcon(url2);
public Animation(){
this.setPreferredSize(new Dimension(128,128));
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addMouseListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(im.getImage(), 0 , 0, im.getIconWidth() - x, im.getIconHeight(), null);
}
public void flipAnimation(){
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//
if (turning) {
x = x + xspeed;
}
repaint();
// x in the middle paint new image & set turning to false to stop animation
if(x >= im.getIconWidth()/2){
turning = false;
x = 0;
im = reverse;
}
}
};
if (turning) {
if (timer != null)timer.stop();
timer = new Timer(30, actionListener);
timer.start();
}
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
e.getSource();
flipAnimation();
}发布于 2016-06-16 16:55:55
首先,我猜您希望您的图像从两边“折叠”,因此您将希望将图像的左侧边缘与其右侧边缘一起增加:
g.drawImage(im.getImage(), x / 2 , 0, im.getIconWidth() - x, im.getIconHeight(), this);注意,第一个int参数已从0更改为x / 2。此外,在用this方法绘制图像时,传递ImageObserver作为paintComponent参数也是很好的做法,因为组件本身就是在图像在背景中加载完之后重新绘制自己的对象。
第二,改变这一点:
if (turning) {
x = x + xspeed;
}对此:
x = x + xspeed;你不需要一个标志来控制动画。(停止动画的正确方法是调用timer.stop(),稍后我将讨论这个问题。)
第三,改变这一点:
if(x >= im.getIconWidth()/2){
turning = false;
x = 0;对此:
if(x >= im.getIconWidth()){
xspeed = -xspeed;turning标志。x与图像的宽度(而不是宽度的一半)进行比较的原因是,只有当第一个图像完全“折叠”时,我们才希望更改图像。xspeed的否定逆转了动画。最后,在actionPerformed方法的末尾,您需要添加以下内容:
if (x <= 0) {
timer.stop();
}当反向图像达到其全部大小时,这将停止动画,这就是不需要turning标志的原因。
https://stackoverflow.com/questions/37864040
复制相似问题