【问题标题】:hitTest on CALayer - how do you find which actual layer was hit?CALayer 上的 hitTest - 你如何找到被击中的实际层?
【发布时间】:2011-11-24 15:51:10
【问题描述】:

情况:需要找到用户触摸了哪一层。

问题:Apple 说我们应该使用 [CALayer presentationLayer] 进行命中测试,以便它代表当时屏幕上的实际内容(它捕获动画中间的信息等)。

...除了:presentationLayer 不返回原始图层,它返回它们的副本...所以:hitTest 将返回一个与原始图层不等效的全新 CALayer 实例。

我们如何找到实际命中的 CALayer?

例如

CALayer* x = [CALayer layer];
CALayer* y = [CALayer layer];
[self.view.layer addSublayer: x];
[self.view.layer addSublayer: y];

...

CALayer* touchedLayer = [self.view.layer.presentationLayer hitTest:touchPoint];

...但是,是触摸层“x”,还是“y”?

if( touchedLayer == x ) // this won't work, because touchedLayer is - by definition from Apple - a new object

【问题讨论】:

    标签: ios calayer


    【解决方案1】:

    亚当的回答是正确的,帮助了我。这是我使用的代码,可以帮助其他人。

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        CGPoint touchPoint = [(UITouch*)[touches anyObject] locationInView:self];
        CALayer *touchedLayer = [self.layer.presentationLayer hitTest:touchPoint];  // is a copy of touchedLayer
        CALayer *actualLayer = [touchedLayer modelLayer];   // returns the actual layer
        NSLog (@"touchedLayer: %@", touchedLayer);
        NSLog (@"actualLayer: %@", actualLayer);
    }
    

    【讨论】:

      【解决方案2】:

      啊!刚刚想通了这一点,阅读有关 CALayer 另一个问题的邮件列表帖子。

      在调用 [CALayer presentationLayer] 并使用 layer-tree 的“演示克隆”后​​,您可以获取该树中的任何对象,并在其上调用 [CALayer modelLayer] 以取回原始参考对象 在原始树中的相同位置

      此参考是稳定的(经过测试 - 有效)。

      Apple 的文档有点……晦涩难懂……关于这个。他们暗示它“有时”会失败(“...results are undefined”)——但现在对我来说已经足够了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-24
        • 2018-10-27
        相关资源
        最近更新 更多