【问题标题】:Shapes drawn at obscure positions在不明显的位置绘制的形状
【发布时间】:2017-02-24 22:29:49
【问题描述】:

这是一个非常奇怪的错误,我似乎无法弄清楚。为了简化这一点,我有三个类:一个 Canvas 类(使用Graphics2D.draw() 绘制对象),然后是许多 ob 家具类,它们可以被视为一个类,因为它们所做的只是返回不同的形状。最后我有一个 CustomShape 类,它可以让我根据现有的其他形状创建一个新的形状。但是这些形状是在奇怪的地方绘制的。 x any y 坐标与绘制形状的位置不匹配。

壁橱.java:

public class Closet {
    double x, y, width, height, rotation;
    Color color;
Closet() {
    this.x = X;
    this.y = Y;
    this.width = 40;
    this.height = 40;
    this.rotation = 0;
    this.color = Color.blue;
}

public Shape getShape() {
    GeneralPath closetShape = new GeneralPath();
    closetShape.append(new Rectangle2D.Double(0, 0, width, height), false);
    closetShape.moveTo(0 , 0);
    closetShape.lineTo(width, height);
    closetShape.moveTo(0, height);
    closetShape.lineTo(width, 0);
    // transform:

    AffineTransform t = new AffineTransform();
    t.translate(x, y);
    Rectangle2D umriss = closetShape.getBounds2D();
    t.rotate(Math.toRadians(rotation),umriss.getX()+umriss.getWidth()/2,umriss.getY()+umriss.getHeight()/2);
      return  t.createTransformedShape(closetShape);
}
}

CustomShape.java

public class CustomShape  {
double x, y, width, height, rotation;
Color color;
private Closet[] c;
CustomShape(Closet... elements) {
    this.m = elements;
    GeneralPath path = new GeneralPath();
    Closet[] newC = elements.clone();
    Arrays.stream(newC).forEach(e -> path.append(e.getShape(), false));
    this.x = path.getBounds2D().getX();
    this.y = path.getBounds2D().getY();
    this.width = path.getBounds2D().getWidth();
    this.height = path.getBounds2D().getHeight();
    this.rotation = 0;
    this.color = Color.blue;
}

public Shape getShape() {
    GeneralPath path = new GeneralPath();
    Arrays.stream(c).forEach(e -> path.append(e.getShape(), false));
    AffineTransform t = new AffineTransform();
    t.translate(x, y);
    Rectangle2D umriss = path.getBounds2D();
    t.rotate(Math.toRadians(rotation),umriss.getX()+umriss.getWidth()/2,umriss.getY()+umriss.getHeight()/2);
    return t.createTransformedShape(path);
}
}

【问题讨论】:

  • 更改 Graphics2D 平移/旋转而不是在形状内进行平移和旋转不是更好吗?这样,形状可以保持不变,您无需每次都创建新形状。

标签: java graphics shape


【解决方案1】:

我找到了解决方案:在将这些形状添加到 CustomShape 之前,我已经对其进行了转换。这就是 x 和 y 坐标错误的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多