如何在 Cocoa 中的给定时间间隔内淡出矩形?
我正在为 OS X 编写一个 Cocoa 应用程序,用户可以通过单击鼠标在 NSView
实例上绘制正方形。目前,我正在使用 NSObject
的 performSelector:withObject:afterDelay:
方法使方块在 2 秒后消失,以强制重绘视图,不包含方块。
然而,我希望这些方块能够逐渐淡出,而不是直接消失。我尝试使用 NSTimer 定期强制重绘,方块的不透明度在 2 秒内降低到 0,但这看起来相当不优雅,而且可能效率低下,特别是如果我有很多方块的话。
有一个惯用的方法来做到这一点吗?
更新:为了澄清,我希望视图中绘制的每个方块从绘制的点开始具有独立的淡入淡出,我不希望淡出整个视图。
I am writing a Cocoa application for OS X, where the user can draw squares on an NSView
instance by clicking with the mouse. Currently I am making the squares disappear after 2 seconds, using the performSelector:withObject:afterDelay:
method of NSObject
, to force a redraw of the view, with no square included.
However, instead of just disappearing, I would like the squares to fade out gradually. I've tried using an NSTimer
to periodically force a redraw, with the opacity of the square decreasing to 0 over 2 seconds, but this seems rather inelegant and probably inefficient, especially if I have a lot of squares.
Is there an idiomatic way to do this?
UPDATE: just to clarify, I want each square drawn in the view to have an independent fade starting from the point at which it's drawn, I'm not looking to fade out the entire view.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终使用的解决方案是为每个正方形创建一个 CALayer 实例,而不是使用 NSRectFill 来绘制正方形。然后可以使用 CABasicAnimation 实例独立地对每个 CALayer 实例的不透明度进行动画处理。例如
The solution I've ended up using is to create a
CALayer
instance for each square, rather than usingNSRectFill
to draw the squares. The opacity of eachCALayer
instance can then be independently animated using aCABasicAnimation
instance. E.g.NSAnimationContext 可能就是你的正在寻找。
NSAnimationContext is probably what you're looking for.