I got the following code:
import java.awt.*;
import javax.swing.*;
public class GraphicPanel extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(new Font("Arial",Font.BOLD,24));
g2d.drawString("A",300,250);
g2d.rotate(45 * Math.PI/180);
g2d.drawString("B",300,250);
}
}
It should rotate B and put it in the same place A is, but for some reason, B apears at a totally different location.
Pretty sure I understand why that is. It's because the entire coordination system is manipulated when scaling, rotating etc (am I correct?)
Anyway, I'd like to know how to rotate or scale an object, and still have it appear where it was before. For example in a game that keeps updating and displaying itself every 10 milliseconds, where a sprite is being rotated, but still stays where it was 10 millisceonds before.
EDIT: Tried to search Google beforehand, guess the wording for this question is kind of tricky because I found nothing helpful.
Thanks a lot :)
To rotate one or more objects, first select the objects to be rotated and choose the Rotate tool. With the Rotate tool active, click and drag anywhere on the canvas to rotate the objects clockwise or counterclockwise. To constrain the rotation to 15˚ increments, hold the Shift ⇧ key while dragging.
Informally: To rotate a shape, move each point on the shape the given number of degrees around a circle centered on the point of rotation. Make sure each new point is the same distance from the point of rotation as the corresponding original point.
When you call the rotate
method on a Graphics2D
object, you're rotating the entire canvas by that angle around the origin. So, drawing a shape at (300, 250) after the rotation will draw it at whatever that point maps to if you started at (300, 250) and then rotated it 45 degrees around (0, 0).
You should use the other form of rotate
that takes the angle as well as the x- and y-coordinates of the rotation pivot point, and pass your point (300, 250) into it. (Although, if you want to rotate around the center of the character or string, you'll need to adjust that point a bit.)
The rotation is done around the origin, e.g. 0,0 of the coordinate system. If you want to rotate around a different point you need to translate the origin, rotate, and translate back, e.g.:
g2d.translate(300, 250);
g2d.rotate(45 * Math.PI/180);
g2d.translate(-300, -250);
g2d.drawString("B",300,250);
Of course you have to take the size of the object you want to rotate in account. This rotates around the point where drawString
would paint, which is the left baseline of the string. Probably you would want to rotate around the center; then you have to measure the object before and add those values to the translation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With