Java中实现图片的旋转功能
一:介绍
主要就是利用Java swing中的一些东西实现的,这个程序就是让图片在GUI页面中显示出来并且点击按钮可以让图片实现旋转的功能。
二:代码
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageChange{
JFrame jf = new JFrame();
public static void main(String[] args){
new ImageChange();
}
public ImageChange(){
inGui();
}
public void inGui(){
TransJPanel canvas = new TransJPanel();
jf.add(canvas);
jf.setBounds(0,0,600,680);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
class TransJPanel extends JPanel{
JButton jb = new JButton("旋转");
BufferedImage img;
BufferedImage img2;
int roteAngle = 0;
public TransJPanel(){
try{
img = ImageIO.read(new File("images\\meinu.png"));
img2 = ImageIO.read(new File("images\\meinufan.png"));
}catch(Exception e){
System.out.println("数据读入有错");
}
this.add(jb);
jb.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("待处理 旋转按钮");
setRotate();
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img,0,0,this);
drawTransImage(g,img.getWidth()+20,img.getHeight()+20);
}
public void drawTransImage(Graphics g,int drawx,int drawy){
int w = img2.getWidth();
int h = img2.getHeight();
Graphics2D g2 = (Graphics2D)g;
g2.translate(drawx,drawy);
if (roteAngle != 0){
g2.rotate(Math.toRadians(roteAngle),w >> 1,h >> 1);
}
g2.drawImage(img2,0,0,w,h,0,0,w,h,null);
g2.translate(-drawx,-drawy);
}
public void setRotate(){
roteAngle += 45;
roteAngle %= 360;
repaint();
}
}
三:效果展示
四:总结
这个代码里面有个问题,就是点击按钮让图片实现旋转的时候,画布中就会多出一个按钮的图片的出来(不过这个按钮是没有用的),暂时不知道如何解决,感觉我也不会回来解决这个问题了。哈哈哈
|