让我们假设我已经创建了一个类似的自定义UIView:
let view = CustomView((frame: CGRect(x: 0, y: 44, width: self.view.frame.width, height: self.view.frame.width))
======
我希望以这种方式旋转它:
// Inside the CustomView
self.transform = CGAffineTransform(rotationAngle: angle)
然后视图不会围绕其中心旋转。但如果视图是这样创建的
let view = CustomView((frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.width))
=====
(我用=====标记了差异)
视图正如预期的那样围绕其中心旋转。我知道旋转中心可以通过anchorpoint调整。但据我所知,CGPoint(0,0)表示“左上角”,CGPoint(0.5,0,5)表示中心,但如果原点的y轴与0不同,则不起作用。
谁能告诉我如何解决这个问题?
答案 0 :(得分:0)
要设置anchorPoint
,请使用以下方法
func setAnchorPoint(_ anchorPoint: CGPoint, for view: UIView) {
var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = newPoint.applying(view.transform)
oldPoint = oldPoint.applying(view.transform)
var position: CGPoint = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
你可以设置锚点......
setAnchorPoint(CGPoint(x: 0.5, y: 0.5), view: view)
然后执行转换。因此它将围绕其锚点转换视图。