【问题标题】:Animate a view's alpha from 0 to 0.5动画视图的 alpha 从 0 到 0.5
【发布时间】:2014-10-05 13:45:41
【问题描述】:

我创建了一个 NSView 作为覆盖视图。在将其添加为另一个视图的子视图后,我想将其 alpha 值从 0 设置为 0.5。我正在执行以下操作,但我从未看到视图的 alpha 动画为 0.5。我知道视图已正确添加,因为如果我将它的背景色设置为具有完整的 alpha,我会看到它。我在这里遗漏了一些简单的东西吗?

self.overlayView = [[MyOverlayView alloc] initWithFrame:frameRect];
self.overlayView.layer.backgroundColor = CGColorCreateGenericRGB(0., 0., 0., 0.0);
[self.window.contentView addSubview:self.overlayView];

__typeof__(self) __weak weakSelf = self;
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
     context.duration = 1;
     weakSelf.overlayView.animator.alphaValue = 0;
}
     completionHandler:^{
         weakSelf.overlayView.alphaValue = 0.5;
}];

我也试过这样的:

[[self.overlayView animator] setAlphaValue:1.0];

【问题讨论】:

  • Can't see a new subview 的可能重复项
  • 这不是那个问题的欺骗。我可以看到新的子视图......它只是没有按照我期望的方式制作动画。
  • 只需替换为这一行 [self.window.contentView addSubview:self.overlayView];用这个 [self.window.contentView.animator addSubview:self.overlayView];动画将正常工作

标签: objective-c cocoa animation nsview alpha


【解决方案1】:

您需要将 wantsLayer 设置为 YES。背景颜色的 alpha 值也应该是 1.0 而不是 0.0。

self.overlayView = [[MyOverlayView alloc] initWithFrame:frameRect];
self.overlayView.wantsLayer=YES;
self.overlayView.layer.backgroundColor = CGColorCreateGenericRGB(0., 0., 0., 1.0);
[self.window.contentView addSubview:self.overlayView];

__typeof__(self) __weak weakSelf = self;
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
     context.duration = 1;
     weakSelf.overlayView.animator.alphaValue = 0;
}
     completionHandler:^{
         weakSelf.overlayView.alphaValue = 0.5;
}];

【讨论】:

  • 我认为只要改变背景颜色就足够了。视图不需要重新分层来获得不透明的alphaValue,也不需要对其进行动画处理。
  • 如果你设置他正在做的图层的背景颜色,他们需要它。我在发布之前测试了答案。
【解决方案2】:

用这一行替换

[self.window.contentView addSubview:self.overlayView];

有了这个

[self.window.contentView.animator addSubview:self.overlayView];

动画会正常工作

【讨论】:

    【解决方案3】:

    你需要 wantsLayer 在你要动画的视图上,还需要 animator 代理对象

    let textField = NSTextField()
    textField.wantsLayer = true
    
    NSAnimationContext.runAnimationGroup({ context in
      context.duration = 1.0
    
      textField.stringValue = "\(emoji.visual) copied to clipboard"
      textField.animator().alphaValue = 1.0
    }, completionHandler: {
       self.textField.alphaValue = 0.0
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2018-12-07
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多