📅  最后修改于: 2023-12-03 15:12:53.469000             🧑  作者: Mango
在Java中,颤动图像可以通过使用Graphics2D对象的rotate()和translate()方法进行实现。这些方法会让图像绕着某个点旋转,同时也可以进行平移操作。
以下是一个简单的实现步骤:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class ShakyImagePanel extends JPanel implements ActionListener {
private ImageIcon imageIcon;
private Timer timer;
private int x, y;
private int angle;
public ShakyImagePanel(String imgPath) {
imageIcon = new ImageIcon(imgPath);
x = y = 0;
angle = 0;
timer = new Timer(100, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), imageIcon.getIconWidth() / 2, imageIcon.getIconHeight() / 2);
g2d.drawImage(imageIcon.getImage(), at, null);
g2d.dispose();
}
@Override
public void actionPerformed(ActionEvent e) {
angle += 30;
x = (int)(Math.random() * 10 - 5);
y = (int)(Math.random() * 10 - 5);
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Shaky Image Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
ShakyImagePanel panel = new ShakyImagePanel("image.jpg");
frame.setContentPane(panel);
frame.setVisible(true);
}
}
下面是一个从网络获取的图片在颤抖效果下的展示效果: