1 个回答

rotate是计算的,可以参考一下demo

import display from '@ohos.display'

function atanToDegrees(atanResult: number) {
  const degrees = atanResult * (180 / Math.PI);
  return degrees < 0 ? degrees + 360 : degrees;
}

function calculateAngleBetweenPoints(p0: Position = {x: 0, y: 0}, p1: Position= {x: 0, y: 0}, p2: Position= {x: 0, y: 0}): number {
  const startY = Number(p1.y) - Number(p0.y)
  const startX = Number(p1.x) - Number(p0.x)
  const startRadians: number = Math.atan2(startY, startX) // 通过反正切函数得到的弧度值

  // 相对于正x轴, 角度范围是0到360度
  const startDeg = atanToDegrees(startRadians)

  const endY = Number(p2.y) - Number(p0.y)
  const endX = Number(p2.x) - Number(p0.x)
  const endRadians: number = Math.atan2(endY, endX)
  const endDeg = atanToDegrees(endRadians)

  return endDeg - startDeg
}

@Entry
@Component
struct SwipeGestureExample {
  @State rotateAngle: number = 0
  @State starPosition: Position = {}
  @State updatePosition: Position = {}
  @State circleCenterPoint: Position = {} // 图片中心点坐标

  private screenH: number = 0
  private screenW: number = 0
  private speed: number = 0

  aboutToAppear(): void {
    let displayClass: display.Display | null = null
    displayClass = display.getDefaultDisplaySync()
    this.screenH = px2vp(displayClass.height)
    this.screenW = px2vp(displayClass.width)
    this.circleCenterPoint = { x: this.screenW / 2, y: this.screenH / 2 }
  }

  build() {
    Column() {
      Stack() {
        Image($r("app.media.background"))
          .width(100)
          .height(100)
          .objectFit(ImageFit.Contain)
          .rotate({
            centerX: '50%',
            centerY: "50%",
            angle: this.rotateAngle
          })

        Circle()
          .width(300)
          .height(300)
          .fillOpacity(0)
          .strokeWidth(2)
          .stroke(Color.Red)
          .onTouch((event: TouchEvent) => {
            if (event.type === TouchType.Down) {
              this.starPosition = { x: event.touches[0].windowX, y: event.touches[0].windowY }
            } else if (event.type === TouchType.Move) {
              this.updatePosition = { x: event.touches[0].windowX, y: event.touches[0].windowY }
            }
            this.rotateAngle = calculateAngleBetweenPoints(this.circleCenterPoint, this.starPosition, this.updatePosition)
            console.log(this.rotateAngle+"==========")
          })
      }
      .hitTestBehavior(HitTestMode.Transparent)
    }
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进