LoginSignup
0
1

More than 1 year has passed since last update.

Swift TopLeft座標上で点を回転させる

Posted at

経緯

移動・回転・伸縮させたViewをUIGraphicsImageRendererで画像化する時に
SwiftUIがくれるViewのposition(親Viewの左上を原点とした子Viewの中心点の位置)ではなく
親Viewの左上を原点とした子Viewの左上の点の位置がほしかった。

point: 親Viewの左上を原点として、回転させる点の位置
centerOfRotation: 親Viewの左上を原点として、回転の中心点の位置
angle: 回転角
scale: 回転後にcenterからの距離を伸縮したい場合に使用

完成品

func rotatePointOnTopLeftCoordinates(point:CGPoint, centerOfRotation center:CGPoint = CGPoint(x:0,y:0), 
angle:Angle, scale:CGFloat = 1)->CGPoint{
    let x = center.x -   ((point.x-center.x) * cos(angle.radians) - (point.y-center.y) * sin(angle.radians)) * scale
    let y = center.y -   ((point.x-center.x) * sin(angle.radians) + (point.y-center.y) * cos(angle.radians)) * scale
    
    let rotatedPoint = CGPoint(x: x, y: y)
    
    return rotatedPoint
}

解説

原点を中心に点A(x:a,y:b)を角度θだけ回転させた点P(x:X,y:Y) は
X = acosθ - bsinθ
Y = asinθ + bcosθ

点A(x:point.x,y:point.x)を回転の中心点center(x:center.x,y:center.y)から見たいので引く。
a = point.x-center.x
b = point.y-center.y

回転させた後scaleを掛けて伸縮させる。
原点視点に戻したいのでx:center.x,y:center.yを足す。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1