在 Javafx 中旋转图像

rotating image in Javafx

ImageView.setRotate(40) 在 Javafx 中使用什么参考点旋转图像?

我在写

ImageView iv = new ImageView(image);
iv.setRotate(40);
SnapshotParameters params = new SnapshotParameters();
params.setFill(Color.TRANSPARENT);
Image rotatedImage = iv.snapshot(params, null);
gc.drawImage(rotatedImage, 0, 0);

但是图片不会相对于图片中心旋转。

来自rotate() documentation

The pivot point about which the rotation occurs is the center of the untransformed layoutBounds.

因此,图像将围绕其中心点旋转。

样本:

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.Canvas;
import javafx.scene.image.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Rotor extends Application {

    public static final String LOC =
            "http://icons.iconarchive.com/icons/custom-icon-design/flatastic-10/64/Bear-icon.png";

    @Override
    public void start(Stage stage) throws Exception {
        ImageView iv = new ImageView(new Image(LOC));
        iv.setRotate(40);

        SnapshotParameters params = new SnapshotParameters();
        params.setFill(Color.TRANSPARENT);
        Canvas canvas = new Canvas(100, 100);

        Image rotatedImage = iv.snapshot(params, null);
        canvas.getGraphicsContext2D().drawImage(rotatedImage, 0, 0);
        stage.setScene(new Scene(new Group(canvas)));

        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

当您在 canvas 上绘制旋转图像时,您可能希望使用 canvas 变换而不是快照方法来帮助完成此操作。参见示例:

  • How to draw image rotated on JavaFX Canvas?