目录

如何实现Matrix2D图形在画布中心点放大并旋转角度

问题现象

如何在画布中心点实现Matrix2D图形指定倍数的放大和指定角度的旋转?

背景知识

解决方案

  1. 使用Flex布局将Canvas组件居中显示,创建矩形。
  2. 使用rotate方法对矩阵进行旋转操作,旋转角度由angle决定,旋转中心为矩形的中心;使用scale方法对矩阵进行缩放操作,缩放倍数由scaleTimesX和scaleTimesY决定,以中心点为基准进行缩放。rotate和scale存在调用顺序,遵循就近原则,因此需要将scale方法的使用放在rotate上方。
  3. 使用translate方法对矩阵进行平移操作,将画布的原点移动到画布的中心,即可将图形移动至画布中心。将经过变换的矩阵应用到CanvasRenderingContext2D对象上。
  4. 用fillRect()方法在画布上绘制矩形。
完整示例参考如下:
@Entry
@Component
struct MatrixChange {
  private settings: RenderingContextSettings = new RenderingContextSettings(true);
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  private matrix: Matrix2D = new Matrix2D();
  x: number = 50; // 图形大小
  y: number = 50; // 图形大小
  canvasWidth: number = 200; // 画布大小
  canvasHeight: number = 200; // 画布大小
  scaleTimesX: number = 2; // 缩放设置
  scaleTimesY: number = 2; // 缩放设置
  angle: number = -30; // 旋转角度

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width(this.canvasWidth)
        .height(this.canvasHeight)
        .backgroundColor('#0D5AF5')
        .onReady(() => {
          this.matrix.scaleX = 1;
          this.matrix.scaleY = 1;
          this.matrix.scale(this.scaleTimesX, this.scaleTimesY);
          this.matrix.rotate(this.angle * Math.PI / 180, this.x / 2, this.y / 2);
          this.matrix.translate(this.canvasWidth / 2, this.canvasHeight / 2);
          this.matrix.translate(-this.x * this.scaleTimesX / 2, -this.y * this.scaleTimesY / 2);
          this.context.setTransform(this.matrix);
          this.context.fillRect(0, 0, this.x, this.y);
        });
    }
    .width('100%')
    .height('100%');
  }
}

总结

Matrix2D图形能够在画布中心点放大指定倍数并旋转指定角度,该功能适用于需要展示图形并对其进行各种变换的场景,例如数据可视化、图形编辑器等。