简单点转换(Graphics2D)

时间:2016-05-11 23:15:29

标签: java graph graphics

我有一个表示图形的简单类,目前它只绘制线条。我目前在绘制之前拦截线条定义,并更改它们的点,但现在我想添加更复杂的形状而不仅仅是点定义。我知道affinetransform,但我不确定如何使用它。我想要一个等同于:

的变换
    private Point transform(PlasmaPoint2D plasmaPoint2D) {
        double x = plasmaPoint2D.getX();
        double y = plasmaPoint2D.getY();
        Point p = new Point();
        p.setLocation(x * this.gridScale / this.scale + this.gridScale, y * this.gridScale / this.scale + this.gridScale);
        return p;
    }

(PlasmaPoint2D是我自己的,不可变的,point2d版本)。 gridScale是一个实例变量,指定每个网格线之间的像素数,scale是单个网格框所代表的单位数。

我不确定如何在AffineTransform中实现此功能,所以我们非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

当从“变换”菜单中选择变换时,变换将连接到AffineTransform上:

public void setTrans(int transIndex) {
    // Sets the AffineTransform.
    switch ( transIndex ) {
    case 0 :
        at.setToIdentity();
        at.translate(w/2, h/2);
        break;
    case 1 :
        at.rotate(Math.toRadians(45));
        break;
    case 2 :
        at.scale(0.5, 0.5);
        break;
    case 3 :
        at.shear(0.5, 0.0);
        break;
    }
}

在显示与菜单选项对应的形状之前,应用程序首先从Graphics2D对象中检索当前变换:

AffineTransform saveXform = g2.getTransform();

在检索当前变换后,会创建另一个AffineTransform toCenterAt,使形状在面板的中心呈现。 at AffineTransform连接到toCenterAt:

AffineTransform toCenterAt = new AffineTransform();
toCenterAt.concatenate(at);
toCenterAt.translate(-(r.width/2), -(r.height/2));

使用transform方法将toCenterAt变换连接到Graphics2D变换:

g2.transform(toCenterAt);

渲染完成后,使用setTransform方法恢复原始变换:

g2.setTransform(saveXform);

答案 1 :(得分:0)

说我有四条曲线:

QuadCurve2D.Double c2=new QuadCurve2D.Double(p[j][0], p[j][1], 
  p[j+1][0], p[j+1][1], p[j+2][0], p[j+2][1]);
int translatebyx=x * this.gridScale / this.scale + this.gridScale-c2.getX1(),
    translatebyy=y * this.gridScale / this.scale + this.gridScale-c2.getY1(), 
  AffineTransform at=AffineTransform.getTranslateInstance(translatebyx, translatebyy);
  Shape s=at.createTransformedShape(c2);
  g2.draw(s);

我希望在指定

时翻译到指定位置
x * this.gridScale / this.scale + this.gridScale,
y * this.gridScale / this.scale + this.gridScale

如果要执行旋转,则应用相同的过程(使用getRotateInstance())等。