[英]How to Make an Image not Resize Because of Rotating it (in JavaFX)?
我有一个旋转图像的方法,并使用drawImage方法将其显示在画布上。 但是,旋转图像时,由于宽度和高度会发生变化(例如旋转正方形,图像的宽度和高度会发生变化),因此图像会缩小和增长。 方法如下:
public void rotateImage(GraphicsContext gc, double speed) {
erase(gc); // erases the previous image
imgView.setRotate(imgView.getRotate() + speed);
SnapshotParameters params = new SnapshotParameters();
params.setFill(Color.TRANSPARENT);
image = imgView.snapshot(params, null);
gc.drawImage(image, pos.x, pos.y, width, height);
}
任何帮助将不胜感激,如有需要,我可以发布其余代码。
具有提供的参数的快照使用父节点中节点的尺寸来确定图像的大小。 在大多数情况下,旋转图像会产生与原始图像不同的尺寸。 在这些情况下,快照大于原始图像。 (考虑将正方形图像旋转45°;旋转后图像的宽度和高度是原始图像对角线的大小,即,以sqrt(2) = 1.41...
的倍数增大)。
由于drawImage
缩放绘制的图像以适合大小为width x height
的矩形,因此将缩小比该大小大的快照。
请改用GraphicsContext
的转换,以避免在每次调用该方法时都创建一个新的Image
实例,并避免缩放图像。
例
@Override
public void start(Stage primaryStage) {
Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/240px-Smiley.svg.png");
Canvas canvas = new Canvas(500, 500);
GraphicsContext context = canvas.getGraphicsContext2D();
Slider slider = new Slider(0, 360, 0);
Button btn = new Button("draw");
VBox root = new VBox(canvas, slider, btn);
btn.setOnAction(evt -> {
context.setFill(Color.TRANSPARENT);
context.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
double posX = 200;
double posY = 150;
context.save();
// apply transformation that puts makes (posX, posY) the point
// where (0,0) is drawn and rotate
context.translate(posX, posY);
context.rotate(slider.getValue());
// draw with center at (0, 0)
context.drawImage(image, -image.getWidth()/2, -image.getHeight()/2);
// undo transformations
context.restore();
});
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.