Reputation: 31
I'm using swt gc for drawing images. One of the option of my program is to rotate the image. I'm also drawing a rectangle as a border. To rotate I'm using following code:
Transform oldTransform = new Transform(gc.getDevice());
gc.getTransform(oldTransform);
Transform transform = new Transform(GCController.getCanvas().getDisplay());
transform.translate(this.x+width/2, this.y+height/2);
transform.rotate(rotation);
transform.scale(this.scaleX, this.scaleY);
transform.getElements(elements);
transform.translate(-this.x-width/2, -this.y-height/2);
gc.setTransform(transform);
gc.drawImage(image, this.x, this.y);
gc.setTransform(oldTransform);
transform.dispose();
After rotation I would like to calculate positions of corners of my rectangle. I was trying something like this:
int tx = (this.x+width/2);
int ty = (this.y+height/2);
double rot = rotation * Math.PI/180;
double newX = tx*Math.cos(rot) - ty*Math.sin(rot);
double newY = tx*Math.sin(rot) + ty*Math.cos(rot);
But it does not working as I expected.
I've also tried using transformation matrix which I'm geting into elements array after each transformation:
int tx = (this.x+width/2);
int ty = (this.y+height/2);
double newX = this.x * elements[0] + this.y * elements[2];
double newY = this.x * elements[1] + this.y * elements[3];
But it gives same results as using equations for rotation. Any ideas ?
I've solved it:
int tx = (-width/2);
int ty = (-height/2);
double rot = rotation * Math.PI/180;
double newX = (tx)*Math.cos(rot) - (ty)*Math.sin(rot) + this.x + width/2;
double newY = (tx)*Math.sin(rot) + (ty)*Math.cos(rot) + this.y + height/2;
I had back to 0,0. Make rotation and after rotation translate it back.
Upvotes: 3
Views: 1957
Reputation: 25543
You just need to multiply the transformation matrix by the position vector for each of the points of your rectangle.
The Transform class presumably has a method for doing this (would make sense), but I can't find readable "swt gc" API documentation, so I can't tell you what it is.
Upvotes: 2