【问题标题】:NSAnimation removes button background colourNSAnimation 移除按钮背景颜色
【发布时间】:2015-04-01 05:57:05
【问题描述】:

我正在开发 Mac 应用程序。我正在尝试做一个简单的动画,使 NSButton 向下移动。动画效果非常好,但是当我这样做时,我的 NSButton 的背景颜色由于某种原因消失了。这是我的代码:

// Tell the view to create a backing layer.
additionButton.wantsLayer = YES;

// Set the layer redraw policy. This would be better done in
// the initialization method of a NSView subclass instead of here.
additionButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
    context.duration = 1.0f;
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0.0, -20.0);
    //additionButton.frame = CGRectOffset(additionButton.frame, 0.0, -20.0);
} completionHandler:nil];

按钮下移动画:

下移动画后的按钮:

更新 1

为了清楚起见,我没有在按钮中使用背景图片。我正在使用我在 viewDidLoad 方法中设置的背景 NSColor,如下所示:

[[additionButton cell] setBackgroundColor:[NSColor colorWithRed:(100/255.0) green:(43/255.0) blue:(22/255.0) alpha:1.0]];

【问题讨论】:

  • 图片不显示
  • @ysaditya 但我没有使用图像作为 NSButton 的背景。我用一个简单的 NSColor 填充它。
  • 您正在使用哪个type 按钮(例如,瞬时按下等)
  • @l'L'l 所以是的,对不起,我的截图是垃圾。但基本上当我在 viewDidLoad 中设置背景单元格颜色时,它工作得很好。当我运行动画时,按钮很好地向下移动,但红色背景颜色完全消失。动画开始后由于某种原因不再有背景颜色。
  • @Supertecnoboff,你应该在[super drawRect]中设置属性

标签: macos cocoa nsbutton nsanimationcontext nsanimation


【解决方案1】:

我认为这是一个 AppKit 错误。有几种方法可以解决它。


解决方法 1:

不要使用图层。您正在制作动画的按钮似乎很小,您可能能够摆脱使用非图层支持的动画并且仍然让它看起来不错。该按钮将在动画的每个步骤中重新绘制,但它会正确地制作动画。这意味着这就是您真正需要做的所有事情:

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {          
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0, -20);
} completionHandler:nil];

解决方法 2:

设置图层的背景颜色。

additionButton.wantsLayer = YES;
additionButton.layer.backgroundColor = NSColor.redColor.CGColor;
additionButton.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {          
    additionButton.animator.frame = CGRectOffset(additionButton.frame, 0, -20);
} completionHandler:nil];

解决方法 3:

子类NSButtonCell,并实现-drawBezelWithFrame:inView:,在那里绘制背景颜色。请记住,包含按钮的父视图应该是图层支持的,否则按钮仍将在每一步重绘。

【讨论】:

  • 非常感谢!!!!!!!我决定使用解决方法 2,因为在阅读了您很棒的网站后,您说图层后置动画更加流畅。再次感谢并感谢他们抽出时间查看我在 Twitter 上发送给您的问题。这个答案已被勾选和投票:D
  • 好交易。确保按钮具有支持图层的父级,否则动画将不会像您期望的那样流畅。
猜你喜欢
  • 2012-04-02
  • 2013-06-24
  • 2020-08-19
  • 2013-08-06
  • 2021-08-10
  • 1970-01-01
  • 2020-11-11
  • 2015-06-04
  • 2019-05-16
相关资源
最近更新 更多