【问题标题】:Animating the mask for a UIView为 UIView 制作蒙版动画
【发布时间】:2013-08-25 20:17:33
【问题描述】:

我可以像这样创建一个面具:

CALayer *mask = [CALayer layer];
    mask.contents = (id)[[UIImage imageNamed:@"mask.png"] CGImage];
    mask.frame = CGRectMake(0, 0, 10, 10);
    self.content.layer.mask = mask;

这将正确显示我内容的左上角 10 像素(因为 mask.png 只是一个黑色图像)。但是我想为面具设置动画以显示其余内容:

 [UIView animateWithDuration:3.0
                     animations:^{
                         mask.frame = self.content.bounds;
                     }
                     completion:^(BOOL finished){

                     }];

问题是没有动画。整个内容会立即显示。为什么会发生这种情况?如何为蒙版设置动画以便从左上角显示内容?

【问题讨论】:

    标签: ios uiview calayer mask uiviewanimation


    【解决方案1】:

    框架是各种其他属性的派生属性,例如位置、边界、锚点以及它应用于它的任何变换。不建议直接为该属性设置动画,尤其是在处理较低级别的 CoreAnimation 图层时。

    在这种情况下,我假设您想要为边界设置动画。可以使用上面的 UIView 动画方法,但是直接处理 CALayers 时我更喜欢使用动画的 CoreAnimation 方法。

    CGRect oldBounds = mask.bounds;
    CGRect newBounds = self.content.bounds;
    
    CABasicAnimation* revealAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"];
    revealAnimation.fromValue = [NSValue valueWithCGRect:oldBounds];
    revealAnimation.toValue = [NSValue valueWithCGRect:newBounds];
    revealAnimation.duration = 3.0;
    
    // Update the bounds so the layer doesn't snap back when the animation completes.
    mask.bounds = newBounds;
    
    [mask addAnimation:revealAnimation forKey:@"revealAnimation"];
    

    【讨论】:

    • 这部分有效。我现在可以看到动画了。然而,它停止了大约一半,而不是显示整个内容视图。你知道为什么会这样吗?
    • 我不敢说实话;仔细检查内容范围内的值是否正确。我也会充实答案,使其更加强大。
    • 其实是因为锚点的原因(默认为0.5,不知为何为0.5)。这修复了它: mask.anchorPoint = CGPointMake(0, 0);
    • 请注意,如果您最终旋转图层,这样的锚点将使旋转枢轴在拐角处,而不是您期望的中心。请参阅developer.apple.com/library/ios/documentation/Cocoa/Conceptual/… 了解更多信息
    猜你喜欢
    • 2012-09-15
    • 1970-01-01
    • 2017-12-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多