如何在 Cocoa 中的给定时间间隔内淡出矩形?

发布于 2024-12-10 03:04:44 字数 396 浏览 0 评论 0原文

我正在为 OS X 编写一个 Cocoa 应用程序,用户可以通过单击鼠标在 NSView 实例上绘制正方形。目前,我正在使用 NSObjectperformSelector: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

佼人 2024-12-17 03:04:44

我最终使用的解决方案是为每个正方形创建一个 CALayer 实例,而不是使用 NSRectFill 来绘制正方形。然后可以使用 CABasicAnimation 实例独立地对每个 CALayer 实例的不透明度进行动画处理。例如

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
[animation setFromValue:[NSNumber numberWithFloat:1.]];
[animation setToValue:[NSNumber numberWithFloat:0.]];
[animation setDuration:2.];
[layer setOpacity:0.];
[layer addAnimation:animation forKey:@"opacity"];

The solution I've ended up using is to create a CALayer instance for each square, rather than using NSRectFill to draw the squares. The opacity of each CALayer instance can then be independently animated using a CABasicAnimation instance. E.g.

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
[animation setFromValue:[NSNumber numberWithFloat:1.]];
[animation setToValue:[NSNumber numberWithFloat:0.]];
[animation setDuration:2.];
[layer setOpacity:0.];
[layer addAnimation:animation forKey:@"opacity"];
风流物 2024-12-17 03:04:44

NSAnimationContext 可能就是你的正在寻找。

NSAnimationContext is probably what you're looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文