将形状旋转90度

时间:2013-04-30 12:19:22

标签: java graphics

我试图将形状旋转90度。

我的形状由一个具有(x,y)点和(point1,point2)线的类保持,所有这些线都组成了这个形状。

实际上,为了将形状旋转90度(或任何其他角度),它应该将形状的点转换为遵循公式 -

(x,y) -> (  x*cos(90)+y*sin(90) , -x*sin(90)+y*cos(90)  )  

所以为了实现上述目的,我尝试了以下(它在每个点上操作,这是形状的组成部分) -

float x, y;
// get the current point location ...
x = currentPoint.x;
y = currentPoint.y; 
// create the cos , sin
float cosA = (float) Math.cos(Math.toRadians(90));
float sinA = (float) Math.sin(Math.toRadians(90));
currentPoint.x = (int) (x * cosA + y * sinA);
currentPoint.y = (int) (-x * sinA + y * cosA);

但是当我在旋转后绘制形状时,它给出了非常奇怪的结果。

你能在这个实现中发现错误吗?

1 个答案:

答案 0 :(得分:1)

您需要扩展JPanel并使用您的类来实现此方法。以下是旋转JPanel控件的代码

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    int w2 = getWidth() / 2;
    int h2 = getHeight() / 2;
    g2d.rotate(-Math.PI / 2, w2, h2);
    super.paintComponent(g);
}

现在使用此自定义类而不是JPanel