一个看似简单的旋转,用了大半天的时间,有必要总结一下。
首先献上网上旋转动画的代码
链接:https://www.jianshu.com/p/f568a55e1f9f
此教程实现了连续旋转,动画结束后,会回到原来的状态,如果我们需要实现图片旋转 90 度的功能就不行了
核心代码:
let oldFrame = imageView.layer!.frame
imageView.wantsLayer = true
let animation = CABasicAnimation.init(keyPath: "transform.rotation")
animation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.linear)
animation.fromValue = 0
animation.toValue = CGFloat.pi / 2
animation.duration = 0.5
animation.repeatCount = 1
let cent_x = imageView.frame.origin.x + imageView.frame.size.width/2
let cent_y = imageView.frame.origin.y + imageView.frame.size.height/2
//旋转锚点
imageView.layer?.anchorPoint = CGPoint.init(x: 0.5, y: 0.5)
//旋转位置
imageView.layer?.position = CGPoint.init(x: cent_x, y: cent_y)
imageView.layer?.add(animation, forKey: nil)
代码略作改进
如何实现旋转 90 度呢
链接:https://developer.apple.com/documentation/appkit/nsview?language=objc
官方提供了以上方法
如何使用呢:
let cent_x = imageView.frame.origin.x + imageView.frame.size.width/2
let cent_y = imageView.frame.origin.y + imageView.frame.size.height/2
let wid = imageView.frame.size.width
let hei = imageView.frame.size.height
let newFrame = CGRect.init(x: cent_x-hei/2, y: cent_y-wid/2, width: hei, height: wid)
imageView.frame = newFrame
imageView.translateOrigin(to: NSPoint.init(x: cent_x, y: cent_y))
imageView.rotate(byDegrees: -90)
currentRotate += 1
需要注意的点:
- imageView是一个 NSImageView,由于NSImageView集成自NSControl,NSControl集成自NSView,此例使用NSImageView没毛病
- imageView要设置的尽可能大一些,以防旋转后图片被挤压
- currentRotate是用来记录旋转角度的
- 由于旋转的是整个控件,所以当用这个控件加载其他的图片的时候,要旋转回去
- 需要重新设置控件的 frame,否则样式会异常,猜测是
translateOrigin
方法中传的点并不贴切导致的
核心代码展示:
//用于记录旋转角度
var currentRotate:Int = 0{
didSet{
if currentRotate == -4 || currentRotate == 4 {
currentRotate = 0
}
print("currentRotete",currentRotate)
}
}
//顺时针旋转 90 度
@IBAction func turnRight90(_ sender: NSButton?) {
let cent_x = imageView.frame.origin.x + imageView.frame.size.width/2
let cent_y = imageView.frame.origin.y + imageView.frame.size.height/2
let wid = imageView.frame.size.width
let hei = imageView.frame.size.height
let newFrame = CGRect.init(x: cent_x-hei/2, y: cent_y-wid/2, width: hei, height: wid)
imageView.frame = newFrame
imageView.translateOrigin(to: NSPoint.init(x: cent_x, y: cent_y))
imageView.rotate(byDegrees: -90)
currentRotate += 1
}
//逆时针旋转 90 度
@IBAction func turnLeft90(_ sender: NSButton?) {
let cent_x = imageView.frame.origin.x + imageView.frame.size.width/2
let cent_y = imageView.frame.origin.y + imageView.frame.size.height/2
let wid = imageView.frame.size.width
let hei = imageView.frame.size.height
let newFrame = CGRect.init(x: cent_x-hei/2, y: cent_y-wid/2, width: hei, height: wid)
imageView.frame = newFrame
imageView.translateOrigin(to: NSPoint.init(x: cent_x, y: cent_y))
imageView.rotate(byDegrees: 90)
currentRotate -= 1
}
恢复旋转角度的代码:
while currentRotate != 0 {
if currentRotate > 0 {
turnLeft90(nil)
}else{
turnRight90(nil)
}
}
网友评论