【问题标题】:Setting mask on CALayer breaks hitTest在 CALayer 上设置掩码会破坏 hitTest
【发布时间】:2013-09-06 00:57:57
【问题描述】:

我有一个CALayer,它的 hitTesting 工作正常。代码是这样的:

- (void)setup
{
    _maskLayer = [CAShapeLayer layer];
    _maskLayer.fillColor = [UIColor whiteColor].CGColor;
    _maskLayer.path = somePath;

    _theLayer.frame = CGRectMake(0, 0, size.width, size.height);
    // Taps work fine if we do not apply the mask
    // _theLayer.mask = _maskLayer;
}

- (IBAction)tapOnView:(UITapGestureRecognizer *)sender
{
    CGPoint point = [sender locationInView:theView];
    CALayer *subLayer = [_theLayer.presentationLayer hitTest:point].modelLayer;

    if (subLayer != _theLayer && subLayer != nil) {
        // Do something with the sublayer which the user touched
    }
}

问题是,如果我取消注释带有mask 的行,我的命中测试总是返回nil。为什么面罩会杀命中测试?它在视觉上看起来是正确的。

【问题讨论】:

    标签: calayer mask hittest


    【解决方案1】:

    事实证明,命中测试要求点在CALayer 的范围内,但没有记录的是它也必须在mask 的范围内。所以我像这样更改了我的代码并且它起作用了:

        _theLayer.frame = CGRectMake(0, 0, size.width, size.height);
    
        // Apply a mask
        _maskLayer.frame = _theLayer.frame;
        _theLayer.mask = _maskLayer;
    

    我花了几个小时才弄清楚这一点,所以我想分享一下。

    【讨论】:

      【解决方案2】:

      我使用了已接受的答案,但仍有一些问题,因为您应该使用边界来防止您的蒙版在您的图层不是 0,0 时不显示此外,这是快速解决方案:

      theLayer.frame = CGRecti(x: 0, y, 0: width: size.width, height:size.height) 
      
      maskLayer.frame = theLayer.bounds
      theLayer.mask = maskLayer
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多