菜鸟教程小白 发表于 2022-12-13 17:24:19

ios - CALayer 中的平滑动画孔?


                                            <p><p>好的,我根据 SO 上的各种帖子想出了如何做到这一点,而且效果很好。我正在研究一个覆盖层,它基本上会掩盖整个窗口,除了一个小区域。这是为了引起对我应用程序特定区域的关注。我正在使用一堆对 <code>moveToPoint:</code> 和 <code>addLineToPoint:</code> 的调用(这是在我的 CALayer 子类的 <code>drawInContext:</code> 中):</p>

<pre><code>....

// inner path (CW)
;
;
;
;

// outer path (CCW)
;
;
;
;

// put the path in the context
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, 0, 0);
CGContextAddPath(ctx, holePath.CGPath);
CGContextClosePath(ctx);

// set the color
CGContextSetFillColorWithColor(ctx, self.overlayColor.CGColor);

// draw the overlay
CGContextDrawPath(ctx, kCGPathFillStroke);
</code></pre>

<p>(<code>holePath</code> 是 <code>UIBezierPath</code> 的一个实例。)</p>

<p>到目前为止一切顺利。下一步是动画。为了做到这一点(我也在 SO 上找到了这个技术)我做了一个方法如下</p>

<pre><code>-(CABasicAnimation *)makeAnimationForKey:(NSString *)key {
    CABasicAnimation *anim = ;
    anim.fromValue = [ valueForKey:key];
    anim.timingFunction = ;
    anim.duration = 0.5;

    return anim;
}
</code></pre>

<p>并覆盖<code>actionForKey:</code>、<code>initWithLayer:</code>和<code>needsDisplayForKey:</code>(返回<code>makeAnimationForKey:</code>的结果在<code>actionForKey:</code>。现在,我得到了一个不错的“洞层”,它有一个属性 <code>holeRect</code> 可以使用隐式 CAAnimations 进行动画处理!不幸的是,它非常不稳定。我得到了类似 2或每秒3帧。我认为可能是背景的问题,并尝试将其替换为快照,但没有骰子。然后,我使用 Instruments 进行分析,发现这里的 HUGE hog 是对 <code> 的调用CGContextDrawPath()</code>.</p>

<p>tl;dr 我想我的问题归结为:有没有更简单的方法来创建这个层,其中有一个孔,可以更快地重绘?我的直觉是,如果我可以简化我正在使用的路径,那么绘制路径会更轻松。或者可能掩盖?请帮忙!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>好的,我尝试了 phix23 的建议,它完全成功了!起初,我将 <code>CALayer</code> 子类化并添加一个 <code>CAShapeLayer</code> 作为子层,但我无法让它正常工作,此时我已经很累了,所以我放弃了,只是用 <code>CAShapeLayer</code> 完全替换了我的子类!我在自己的方法中使用了上面的代码,返回 <code>UIBezierPath</code>,并像这样动画:</p>

<pre><code>UIBezierPath* oldPath = ;
UIBezierPath* newPath = ;
self.holeRect = rectToHighlight;

CABasicAnimation *animation = ;
animation.duration = 0.5;
animation.timingFunction = ;
animation.fromValue = (id)oldPath.CGPath;
animation.toValue = (id)newPath.CGPath;
;
self.holeLayer.path = newPath.CGPath;
</code></pre>

<p>有趣的附注——<code>path</code> 不是隐式可动画的。我想这是有道理的。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - CALayer 中的平滑动画孔?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/13080440/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/13080440/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - CALayer 中的平滑动画孔?