Swift AppKit - NSView Fade-In 动画实现
要给NSView加入Fade-In动画,可以使用NSAnimation和NSView的alphaValue属性来实现。
首先,在NSView的初始化方法中设置alphaValue为0,将视图的alpha值设置为0,这样视图将会是透明的。
然后,创建一个NSAnimation对象,并设置其duration属性为动画的持续时间。
接着,实现NSAnimation的animationDidEnd方法,在动画结束时将视图的alpha值设置为1,即完全显示。
最后,调用NSAnimation的startAnimation方法,开始动画。
下面是一个示例代码:
import Cocoa
class MyView: NSView {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.wantsLayer = true
self.layer?.backgroundColor = NSColor.red.cgColor
self.alphaValue = 0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func fadeIn() {
let animation = NSAnimation(duration: 1, animationCurve: .easeIn)
animation.animationBlockingMode = .nonblockingThreaded
animation.delegate = self
animation.startAnimation()
}
}
extension MyView: NSAnimationDelegate {
func animationDidEnd(_ animation: NSAnimation) {
self.alphaValue = 1
}
}
在需要添加Fade-In动画的地方调用视图的fadeIn方法即可。
原文地址: https://www.cveoy.top/t/topic/qfiA 著作权归作者所有。请勿转载和采集!