有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaFX如何围绕它的中心旋转图形

我对旋转法有问题。我想围绕图形的中心旋转图形,但我不想旋转画布对象,只旋转其中的图形。 artHorizon是画布对象(400400) 或者将坐标系移到convas对象的中心会更好

以下是一种绘图方法:

public void drawHorizon(GraphicsContext gc, double degrees, double translate) {

        gc.translate(0, translate);

        gc.rotate(degrees);

        gc.setFill(Color.rgb(0, 61, 144));
        gc.fillRect(0, 0, artHorizon.getWidth() * 2, 150);
        gc.setFill(Color.rgb(59, 41, 39));
        gc.fillRect(0, 150, 400, 150);

    }

并初始化:

@Override
    public void initialize(URL location, ResourceBundle resources) {

        GraphicsContext gc = artHorizon.getGraphicsContext2D();
        gc.rotate(20);//here I want to rotate gc around center
        drawHorizon(gc, 0, 0);


    }

共 (2) 个答案

  1. # 1 楼答案

    您可以通过指定给Affine的构造函数的适当透视来传递Rotate。结果可以传递给GraphicsContexttransform方法。此外,为了确保将Canvas归档到其边缘,请添加一些偏移量。Canvas的最大尺寸肯定足够:

    gc.transform(new Affine(new Rotate(20, artHorizon.getWidth()/2, artHorizon.getHeight()/2)));
    // gc.rotate(20);
    
    public void drawHorizon(GraphicsContext gc, double degrees, double translate) {
        gc.translate(0, translate);
    
        gc.rotate(degrees);
        double maxDimension = Math.max(artHorizon.getWidth(), artHorizon.getHeight());
    
        gc.setFill(Color.rgb(0, 61, 144));
        gc.fillRect(-maxDimension, 0, maxDimension * 3, 150);
        gc.setFill(Color.rgb(59, 41, 39));
        gc.fillRect(-maxDimension, 150, maxDimension * 3, 150);
    }
    
  2. # 2 楼答案

    如果要围绕点旋转

    将现有变换替换为新变换,然后旋转。setTransform最后两个值是新原点的画布像素坐标,其中x=0和y=0

    gc.setTransform(1.0, 0.0, 0.0, 1.0, artHorizon.getWidth() / 2.0, 150.0);
    gc.rotate(degrees);
    

    原点现在位于artHorizon.getWidth() / 2150.0,因此必须从该点开始绘制。您将需要对角线宽度,以便填充整个画布

    double len = Math.sqrt(
           artHorizon.getWidth() * artHorizon.getWidth() + 
           artHorizon.getHeight() * artHorizon.getHeight()) / 2.0;
    

    然后渲染距原点的地平线偏移

    gc.fillRect(-len, -150, len * 2, 150); // top half
    // change colour
    gc.fillRect(-len, 0, len * 2, 400); // bottom half
    

    您可以使用将画布返回到默认值

    gc.setTransform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);