1
    AffineTransform at;
    Graphics2D g2 = (Graphics2D)g;

    g2.setColor(Color.black);

    at = new AffineTransform();
    at.setToTranslation(x, y);
    at.setToRotation(theta);
    g2.setTransform(at);
    g2.drawPolygon(points);

我的代码在 x 和 y 处绘制了一个三角形……当我按下 a 和 d 时,三角形旋转……但是当我按下 w 和 s 时,三角形不会改变它的 x 和 y。

变量是正确的..这是翻译例程..我不确定我错在哪里..

如果我这样做:

    AffineTransform at;
    Graphics2D g2 = (Graphics2D)g;

    g2.setColor(Color.black);

    at = new AffineTransform();
    at.setToTranslation(x, y);
    g2.setTransform(at);
    g2.drawPolygon(points);

    at.setToRotation(theta);
    g2.setTransform(at);
    g2.drawPolygon(points);

一个旋转一个移动.. 那么为什么我不能在绘图之前应用这两种翻译呢?

4

3 回答 3

0

来自 Oracle 文档:

要添加坐标变换,请使用变换、旋转、缩放或剪切方法。setTransform 方法仅用于在渲染后恢复原始 Graphics2D 变换。

只能有一个转换,您可以在其中连接新的转换,例如旋转方法:

Concatenates the current Graphics2D Transform with a translated rotation transform. Subsequent rendering is transformed by a transform which is constructed by translating to the specified location, rotating by the specified radians, and translating back by the same amount as the original translation.

There is also a warning:

WARNING: This method should never be used to apply a new coordinate transform on top of an existing transform because the Graphics2D might already have a transform that is needed for other purposes, such as rendering Swing components or applying a scaling transformation to adjust for the resolution of a printer.

于 2012-10-02T19:18:36.013 回答
0

I think you need to concatenate both transformations into a single AffineTransformation.

i.e.

AffineTransform at, toConcatenate;
Graphics2D g2 = (Graphics2D)g;

g2.setColor(Color.black);

at = new AffineTransform();
toConcatenate = new AffineTransform();

at.setToTranslation(x,y);
toConcatenate.setToRotation(theta);
at.concatenate(toConcatenate);
g2.setTransform(at)
g2.drawPolygon(points);

I based much of this on a tutorial found on Oracles site at http://docs.oracle.com/javase/tutorial/2d/advanced/transforming.html

I think the reason your code doesn't work is that 'The setTransform method overwrites the Graphics2D object's current transform' You're overwriting the first transform with the second rather than concatenating the two.

Hope this helps

于 2012-10-02T19:58:55.120 回答
0
    AffineTransform at;
    Graphics2D g2 = (Graphics2D)g;

    g2.setColor(Color.black);

    at = new AffineTransform();

    at.translate(x, y);     
    at.rotate(theta);
    g2.setTransform(at);
    g2.drawPolygon(points);

I was using the wrong things.. rotate and translate are the functions i needed.

于 2012-10-02T23:12:49.543 回答