【发布时间】:2019-12-24 10:58:15
【问题描述】:
我想将点旋转 -90 度
初始
决赛
让我们看一下 Initial 的左上角和右上角。它们的坐标是:
let topLeft = CGPoint(x: 2, y: 1)
let topRight = CGPoint(x: 3, y: 1)
旋转后它们的坐标应该变成:
topLeft 1:0
topRight 2:0
我该怎么做?
我尝试了几个答案,但没有一个给出我的最终结果。
没用: Rotating a CGPoint around another CGPoint
What is the best way to rotate a CGPoint on a grid?
以下是我操场上的一些代码:
let topLeft = CGPoint(x: 2, y: 1)
let topRight = CGPoint(x: 3, y: 1)
func rotatePoint1(_ point: CGPoint, _ degrees: CGFloat) -> CGPoint {
let s = CGFloat(sinf(Float(degrees)))
let c = CGFloat(cosf(Float(degrees)));
return CGPoint(x: c * point.x - s * point.y, y: s * point.x + c * point.y)
}
func rotatePoint2(_ point: CGPoint, _ degrees: CGFloat, _ origin: CGPoint) -> CGPoint {
let dx = point.x - origin.x
let dy = point.y - origin.y
let radius = sqrt(dx * dx + dy * dy)
let azimuth = atan2(dy, dx) // in radians
let newAzimuth = azimuth + degrees * CGFloat(M_PI / 180.0) // convert it to radians
let x = origin.x + radius * cos(newAzimuth)
let y = origin.y + radius * sin(newAzimuth)
return CGPoint(x: x, y: y)
}
func rotatePoint3(_ point: CGPoint, _ degrees: CGFloat) -> CGPoint {
let translateTransform = CGAffineTransform(translationX: point.x, y: point.y)
let rotationTransform = CGAffineTransform(rotationAngle: degrees)
let customRotation = (rotationTransform.concatenating(translateTransform.inverted())).concatenating(translateTransform)
return point.applying(customRotation)
}
print(rotatePoint1(topLeft, -90))
print(rotatePoint1(topRight, -90))
【问题讨论】:
-
您的
topLeft在围绕中心点旋转-90 后变为左下角(1:1)(并且topRight 变为左上角),因此值得更清楚地指定问题。
标签: ios swift math rotation cgpoint