更改锚点

在iOS中,锚点是按照百分比计算的,也就说,默认的点是0.5,0.5;我们现在需要计算黑胶唱片指针的圆角中心的百分比。

例如:当前图片宽高为:276 × 414。

旋转点为(50,50)。

所以锚点为:x=50/276=0.181,y=50/414=0.120。保留三位小数。

如何更改锚点

锚点的更改很简单,直接更改view的layer.anchorPoint,代码如下:

/// 更改View锚点
/// 会自动修正位置的偏移
///
/// - Parameter anchorPoint: <#anchorPoint description#>
func setViewAnchorPoint(_ anchorPoint:CGPoint) {
    //原来的锚点
    let originAnchorPoint = layer.anchorPoint
    
    //要偏移的锚点
    let offetPoint = CGPoint(x: anchorPoint.x - originAnchorPoint.x, y: anchorPoint.y - originAnchorPoint.y)
    
    //要偏移的距离
    let offetX=(offetPoint.x) * frame.size.width
    let offetY=(offetPoint.y) * frame.size.height
    
    //设置这个值 说明已经改变了偏移量
    layer.anchorPoint = anchorPoint
    
    //将指定的偏宜量更改回来
    layer.position = CGPoint(x: layer.position.x + offetX, y: layer.position.y + offetY)
}

使用:

setViewAnchorPoint(CGPoint(x: 0.181, y: 0.120))

版权声明:本文为zhangxun_yu1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。