I created a rectangle in java using graphics2D and I want to rotate it over all axis, Ox, Oy and Oz in origin (0,0). How to do that ?
Because it's 2D, z = 0. So can you help me to rotate this rectangle over all axis ?
Thank you!
This is my code, I created a rectangle and I want to save it as image.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class DrawShape_SaveAsImage extends Canvas {
public static void main(String[] args) {
Frame f=new Frame("Draw shape and text on Canvas");
final Canvas canvas=new DrawShape_SaveAsImage();
f.add(canvas);
f.setSize(600,600);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
saveCanvas(canvas);
System.exit(0);
}
});
}
public void paint(Graphics g) {
Graphics2D g2=(Graphics2D)g;
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
g2.setColor(Color.BLACK);
g2.fillRect(100, 100, 200, 200);
}
public static void saveCanvas(Canvas canvas) {
BufferedImage image=new BufferedImage(canvas.getWidth(), canvas.getHeight(),BufferedImage.TYPE_INT_RGB);
Graphics2D g2=(Graphics2D)image.getGraphics();
canvas.paint(g2);
try {
ImageIO.write(image, "png", new File("canvas.png"));
} catch (Exception e) {
}
}
}
This is 2D so you can rotate around OZ only. First of all you should use Vectors for any coordinates (it makes math easy ;) ) Here you have the example of Vector class and rotation. You can check demo coded by me here: http://ideone.com/ZZjm6l
import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.Math.*;
class Vector
{
double x;
double y;
Vector(double a, double b)
{
x = a;
y = b;
}
void add(Vector v)
{
x += v.x;
y += v.y;
}
//other useful methods like multiply should be here
void rotate(double angle) //https://en.wikipedia.org/wiki/Rotation_(mathematics)
{
double s = sin(angle);
double c = cos(angle);
x = x * c - y * s;
y = x * s + y * c;
}
}
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Vector v = new Vector(1,1);
v.rotate(Math.PI / 2);
System.out.println(v.x + " " + v.y);
}
}
So your fillRect should look like this after all:
g2.fillRect(v.x, v.y, 200, 200);
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.