繁体   English   中英

CALayer 中的事件

[英]Events in CALayer

我在我的代码中使用 CALayers animation。 下面是我的代码

CALayer *backingLayer = [CALayer layer];
        backingLayer.contentsGravity = kCAGravityResizeAspect;
        // set opaque to improve rendering speed
        backingLayer.opaque = YES;


        backingLayer.backgroundColor = [UIColor whiteColor].CGColor;

        backingLayer.frame = CGRectMake(0, 0, templateWidth, templateHeight);

        [backingLayer addSublayer:view.layer];
        CGFloat scale = [[UIScreen mainScreen] scale];
        CGSize size = CGSizeMake(backingLayer.frame.size.width*scale, backingLayer.frame.size.height*scale);
        UIGraphicsBeginImageContextWithOptions(size, NO, scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [backingLayer renderInContext:context];

        templateImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

这个backingLayer有很多这样添加的sublayer,这个view就是我的subView。 但是现在我如何在各自的 UIViews 中获取视图的事件,因为我已经将它们添加为子层,我正在尝试实现类似于 Flipboard 应用程序的东西,即使它们是子层,它们也有页面导航和点击事件。

CALayers 的要点在于它们重量轻,特别是没有事件处理开销。 这就是 UIView 的用途。 您的选择是将您的代码转换为使用 UIViews 进行事件跟踪,或者编写您自己的事件传递代码。 对于第二个,基本上,你会让你的包含 UIView 对每个子层的边界做一堆“是矩形的点”查询,并将事件传递给(自定义方法)具有最高 z 位置的 CALayer .

正如 claireware 提到的,CALayers 不直接支持事件处理。 但是,您可以捕获包含 CALayer 的 UIView 中的事件,并向 UIView 的隐式层发送“hitTest”消息以确定触摸了哪个层。 例如:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    CALayer *target = [self.layer hitTest:location];
    // target is the layer that was tapped
} 

以下是 Apple 文档中有关 hitTest 的更多信息:

Returns the farthest descendant of the receiver in the layer hierarchy (including itself) that contains a specified point.

Return Value
The layer that contains thePoint, or nil if the point lies outside the receiver’s bounds rectangle.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM