旋转后的矩形坐标

时间:2011-05-09 10:12:38

标签: java graphics swt

我正在使用swt gc绘制图像。我的程序的一个选项是旋转图像。我也画一个矩形作为边框。要旋转我正在使用以下代码:

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();

旋转后,我想计算矩形角的位置。 我正在尝试这样的事情:

    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);

但它没有像我预期的那样发挥作用。

我也尝试过使用转换矩阵,我会在每次转换后将其转换为元素数组:

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];

但它给出了与使用旋转方程式相同的结果。有什么想法吗?

我已经解决了:

    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;

我回到了0,0。旋转和旋转后将其转换回来。

1 个答案:

答案 0 :(得分:1)

您只需要将变换矩阵乘以矩形的每个点的位置矢量。

Transform类可能有这样做的方法(有意义),但我找不到可读的“swt gc”API文档,所以我不能告诉你它是什么。

相关问题