3 回答
TA贡献1773条经验 获得超3个赞
代码有问题。
帮你改好了,你试试
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyPanel extends JPanel {
private int xuanzhuan = 0;
private Image image;
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(0, 0, 400, 400);
g2d.rotate(xuanzhuan, 200, 200);
image = new ImageIcon("src/test.jpg")
.getImage();
g2d.drawImage(image, 0, 0, this);
g.dispose();
}
public Image getImage() {
return image;
}
public int getXuanzhuan() {
return xuanzhuan;
}
public void setXuanzhuan(int xuanzhuan) {
this.xuanzhuan = xuanzhuan;
}
}
public class DrawImage implements ActionListener {
JFrame frame; // 主窗体
MyPanel panel;
JButton rotate; // 控制旋转的按钮
public DrawImage() {
frame = new JFrame("绘图Demo");
frame.setSize(400, 500);
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
panel = new MyPanel();
panel.setBounds(0, 0, 400, 400);
frame.getContentPane().add(panel);
rotate = new JButton("逆旋"); // 每按一次逆时针旋转90度
rotate.setBounds(5, 405, 390, 90);
frame.getContentPane().add(rotate);
rotate.addActionListener(this);
}
public static void main(String[] args) {
new DrawImage();
}
public void actionPerformed(ActionEvent e) {
panel.setXuanzhuan(panel.getXuanzhuan() + 1);
panel.repaint();
}
}
TA贡献1818条经验 获得超7个赞
ctx = document.getElementByIdx_x_x_x('canvas').getContext('2d');
ctx.fillStyle = "rgb(250,0,0)";
ctx.save();
ctx.translate(50,50); //这个translate(50,50)发生在rotate()之前,其目的是将旋转点从默认点(0,0),移动到(50,50),下面紧跟着的rotate就是按照这个点来转
//rotate方法的旋转点完全是按照[在其上\紧跟着它的]translate来确定旋转点的.
ctx.rotate(-Math.PI/8);
ctx.translate(-50,-50);//这个translate是在rotate之下,也就是rotate已经转过了再执行translate(-50,-50),它其实也是将坐标点从(50,50)重新移到了(0,0),紧跟在他下面的rotate旋转中心就是按照(0,0)来旋转的
ctx.fillRect(50,50,100,200);
//ctx.beginPath();
ctx.fillStyle="rgb(0,255,0)"
ctx.rotate(-Math.PI/6);
ctx.fillRect(50,50,100,200);
ctx.restore();
ctx.fillStyle = "rgb(0,0,250)";
ctx.fillRect(50,50,5,5);
总结:这里的translate就是移动中心点的.旋转中心默认是在canvas的左上角.
- 3 回答
- 0 关注
- 330 浏览
添加回答
举报