【问题标题】:How to custom CALayer using subclassing如何使用子类化自定义 CALayer
【发布时间】:2012-01-18 05:38:26
【问题描述】:

在 UIView 上有许多 CALayer。每个 CALayer 由 CAShapeLayers 组成。 CAShapeLayers 的路径属性由 UIBezierPath 组成。

我的目标是当我点击 CALayer 时,我想获得在 UIBezierPath 绘图中使用的点。为此,我想到了将具有 NSMutableArray 的 CALayer 子类化来存储点。当我特别绘制 CALayer 时,我会节省积分。因此,每当我点击特定的 CALayer 时,我都会获得与之相关的积分。我也想给每个 CALayer 打标签。我不知道该怎么做。

第二种方法是使用 CALayer 的内置属性,它会给我在 CALayer 中捕获的分数。但我不知道这种属性。

请分享你的想法如何完成这项任务?

【问题讨论】:

    标签: iphone calayer quartz-graphics cashapelayer


    【解决方案1】:

    您将需要使用包含 CALayer 的 UIView 来处理触摸事件,CALayer 没有内置的触摸事件。 - (CALayer *)hitTest:(CGPoint)thePoint 返回触摸事件点所在的“最深”CALayer。因此,如果您调用[self.layer hitTest:point],它将检查您的所有子层并返回正确的CALayer

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        CGPoint point = [[touches anyObject] locationInView:self];
        CALayerSubclass *taplayer = [self.layer hitTest:point]
        NSArray *points = [taplayer getPoints];
    }
    

    没有办法从 CGPath 中取出你输入的点。你能做的最好的事情是these methods 关于从路径获取信息。所以,就像你说的那样,你最好的办法是继承 CALayer 并将你需要的所有信息放在一个数据结构中以便以后检索。

    // .h
    @interface CALayerSubclass : CALayer
    
    @property (nonatomic, strong) NSMutableArray *points;
    
    @end
    
    // .m
    -(void)drawInContext:(CGContextRef)ctx {
        ...
        [bezierPath addCurveToPoint:controlPoint1:point1 controlPoint2:point2];
        [points addObject:[NSValue valueWithCGPoint:point1]];  
        [points addObject:[NSValue valueWithCGPoint:point2]];  
        ...
    }
    

    只需将所有 CGPoints(或大多数其他核心图形结构)存储在 NSValue 中,然后将其放入数组中。

    【讨论】:

    • 我实际上想从包含路径绘图的 CALayer 中检索所有点。该怎么做?
    • 哎呀,对不起。误读了你的问题。希望我的编辑有所帮助。
    • 请注意 -drawInContext: 在 CAShapeLayer 中不会被调用。
    • 想详细说明一下?它没有被显式调用,但如果使用得当,它将在 CALayerSubclass 对象上调用“setNeedsDisplay”之后。
    • @ProudMember -drawInContext 如果您将其帧大小(宽度/高度)设置为非零值,则会在 CAShapeLayer 中调用
    猜你喜欢
    • 1970-01-01
    • 2011-01-24
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多