【问题标题】:UILabel animation beyond bounds of UILabel超出 UILabel 范围的 UILabel 动画
【发布时间】:2014-07-07 13:46:57
【问题描述】:

我有一个标签,我想要一个“速度计”效果;当为标签的文本分配新值时,我希望旧值向上滚动,新值从下方进入。我不知道如何实现这一目标。这是我目前正在使用的;

  CATransition *animation = [CATransition animation];
  animation.duration = .2f;
  animation.type = kCATransitionPush;
  animation.subtype = kCATransitionFromBottom;
  animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
  animation.removedOnCompletion = YES;

  [mylabel.layer addAnimation:animation
                       forKey:@"changeTextTransition"];

  mylabel.text = @"new text";

这工作得很好,除了顶部和底部的过渡在褪色之前超出了标签的范围。我希望将过渡效果包含在标签的范围内。

我试图为图层创建一个蒙版,并将图层蒙版设置为边界,但这没有效果:

  UIImageView *maskView = [[UIImageView alloc] initWithImage:labelMask];
  // this image is a png that is the same dimensions as the label, and is 100% opaque and colored white
  maskView.frame = mylabel.frame;
  mylabel.layer.mask = maskView.layer;
  mylabel.layer.masksToBounds = YES;

我什至尝试了另一种创建蒙版的方法:

  CALayer *maskLayer = [CALayer new];
  maskLayer.frame = mylabel.frame;
  maskLayer.contents = (id)(labelMask.CGImage); // same image as above
  maskLayer.contentsRect = mylabel.bounds;
  mylabel.layer.mask = maskLayer;
  mylabel.layer.masksToBounds = YES;

这没有效果。

我还可以尝试什么来防止图层动画泄漏到 UILabel 的边界之外?

【问题讨论】:

  • 这可能很明显,但是 `myLabel.clipToBounds = YES;' 呢?
  • @rmaddy 这行不通,因为我正在为 UILabel 的 CALayer 设置动画; UILabel 不能对其自己的层施加任何控制。下面 daniel.gindi 的回答通过将 UILabel 放在另一个容器 (UIView) 中并强制该容器控制其子视图的行为(在本例中为 view clipsToBounds)来解决问题。

标签: ios uilabel core-animation calayer


【解决方案1】:

您正在使用动画移动UILabel 的图层本身,而UILabelclipsToBounds (UIView)/masksToBounds (CALayer) 将UILabel 的图层本身作为一个整体进行了限制.

为了更清楚地说明:如果您将在UILabel放置一些东西,或者尝试在标签的图层上渲染更大的东西,它将被蒙版剪裁。但是,如果您只是将标签移动到父视图上的其他位置 - 那么它会保持完整,因为蒙版会随之移动......

即使在制作动画时,情况也完全相同。蒙版随图层移动。

因此,解决方案将UILabel 包含在另一个UIView 中,该UIView 本身具有clipsToBounds 集。 这也将允许您创建 UIView 的子类,它是一个迷你控制器,管理自己的标签,根据需要使用 UIView 子类上的简单接口为它们设置动画等。 (我猜这就是你正在做的事情,你只是忘了在容器视图上设置clipsToBounds...)

【讨论】:

  • 你好!感谢您的解释,非常有启发性。
  • 如果我缩小边界然后在使用自动布局时为文本大小设置动画,则不会显示完整的标签文本。即使将标签放在视图中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多