颤动 - 如何使用画布围绕中心旋转图像

问题描述 投票:0回答:1

我正在尝试实现一个可以在画布上绘制图像(缩小版本)的自定义画家,并且可以旋转和缩放绘制的图像。

我知道要缩放图像我必须使用缩放方法缩放画布。

现在的问题是如何在其中心(或任何其他点)旋转缩放图像。画布的旋转方法只允许在左上角旋转。

Here is my implementation that can be extended

dart flutter
1个回答
3
投票

figure 1 figure 2

这可以通过移动坐标空间来实现,如图1所示。平移是C1和C2之间坐标的差异,正如图2中的A和B之间的差异。通过一些几何公式,我们可以计算出所需的平移和产生旋转图像,如下面的方法

ui.Image rotatedImage({ui.Image image, double angle}) {
  var pictureRecorder = ui.PictureRecorder();
  Canvas canvas = Canvas(pictureRecorder);

  final double r = sqrt(image.width * image.width + image.height * image.height) / 2;
  final alpha = atan(image.height / image.width);
  final beta = alpha + angle;
  final shiftY = r * sin(beta);
  final shiftX = r * cos(beta);
  final translateX = image.width / 2 - shiftX;
  final translateY = image.height / 2 - shiftY;
  canvas.translate(translateX, translateY);
  canvas.rotate(angle);
  canvas.drawImage(image, Offset.zero, Paint());

  return pictureRecorder.endRecording().toImage(image.width, image.height);
}

alpha,beta,angle都是弧度的。

这是demo app的回购

© www.soinside.com 2019 - 2024. All rights reserved.