通过淡入淡出效果对CALayer蒙版进行动画处理 [英] Animate CALayer mask change with fade effect

查看:62
本文介绍了通过淡入淡出效果对CALayer蒙版进行动画处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIView ,其中 view.layer.mask 设置为 CAShapeLayer 。形状层包含一条路径,现在我想通过添加具有偶数/奇数规则的第二个形状并为该形状添加一个孔,并淡入该孔的外观。

I have a UIView, with view.layer.mask set to an instance of CAShapeLayer. The shape layer contains a path, and now I want to add a hole to this shape by adding a second shape with even/odd rule, and fade-in the appearance of this hole.

问题是添加到路径似乎不是可动画的:

The problem is that adding to path doesn't seem to be animatable:

[UIView animateWithDuration:2 animations:^() {
    CGPathAddPath(parentPath, nil, holePath);
    [v.layer.mask didChangeValueForKey:@"path"];
}];

我该如何设置动画?

推荐答案

经过一番摆弄之后,找到了一种解决方法:

After some fiddling, found a workaround:


  1. 创建一个包含两个具有两个所需形状的子图层的图层,并将其用作蒙版

  2. 第一个子层(无孔)的动画不透明度从1到0。

之所以起作用,是因为子 CAShapeLayer 实例似乎被用作联合。隐藏第一个没有孔的子层时,只会发现孔,共享区域不会更改。

This works because child CAShapeLayer instances appear to be used as a union. When you hide the first sublayer without a hole, only the hole will be uncovered, the shared area will not change.

CGMutablePathRef p = CGPathCreateMutable();

// First path
CGPathAddPath(p, nil, outerPath);
CAShapeLayer *mask1 = [CAShapeLayer layer];
mask1.path = p;

// 2nd path with a hole
CGPathAddPath(p, nil, innerPath);
CAShapeLayer *mask2 = [CAShapeLayer layer];
mask2.path = p;
mask2.fillRule = kCAFillRuleEvenOdd;

CGPathRelease(p);

// Create actual mask that hosts two submasks
CALayer *mask = [CALayer layer];
[mask addSublayer:mask1];
[mask addSublayer:mask2];
myView.layer.mask = mask;
mask.frame = v.layer.bounds;
mask1.frame = mask.bounds;
mask2.frame = mask.bounds;

// ...

// Hide mask #1
CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"opacity"];
a.fromValue = @1.0;
a.toValue = @0.0;
a.duration = 1.0;
a.fillMode = kCAFillModeForwards; // Don't reset back to original state
a.removedOnCompletion = NO;
[mask1 addAnimation:a forKey:@"hideMask1"];

这篇关于通过淡入淡出效果对CALayer蒙版进行动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆