我有一个旋转图像的方法,并使用drawImage方法将其显示在画布上。但是,旋转图像时,由于宽度和高度会发生变化(例如旋转正方形,图像的宽度和高度会发生变化),因此图像会缩小和增长。方法如下:
<div id="root">
<div class="container">
<div class="header">
header
</div>
<div class="main">
<div class="main-container">
<div class="topleft">
topleft
</div>
<div class="topright">
topright
</div>
<div class="bottomleft">
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>bottomleft</div>
<div>last</div>
</div>
<div class="bottomright">
bottomright
</div>
</div>
</div>
<div class="aside">
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>aside</div>
<div>last</div>
</div>
</div>
</div>
任何帮助将不胜感激,如有需要,我可以发布其余代码。
答案 0 :(得分:2)
具有提供的参数的快照使用父节点中节点的尺寸来确定图像的尺寸。在大多数情况下,旋转图像会产生与原始图像不同的尺寸。在这些情况下,快照大于原始图像。 (请考虑将方形图像旋转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();
}