如何使用子类化定制CALayer
问题描述:
在UIView上有许多CALayer。每个CALayer由CAShapeLayers组成。 CAShapeLayers的路径属性由UIBezierPath组成。如何使用子类化定制CALayer
我的目标是当我点击CALayer时,我想要得到我在绘制UIBezierPath时使用的点。为此,我想到子类CALayer有NSMutableArray存储点。当我特别绘制CALayer时,我将节省点数。所以每当我点击特定的CALayer时,我都会得到与之相关的点数。我也想给每个CALayer标签。我不知道该怎么做。
第二种方法是使用CALayer的内置属性,这会让我在CALayer中捕获点数。但我不知道这种财产。
请分享您的想法如何完成此任务?
答
您将需要使用包含CALayer的UIView来处理触摸事件,CALayers没有内置的触摸事件。 - (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]];
...
}
只是存储在一个NSValue所有CGPoints(或其他大多数核芯显卡结构),把它扔进一个数组。
我其实想要从包含路径绘制的CALayer中检索所有点。怎么做? – Harsh 2012-01-20 05:20:26
哎呀,对不起。错读你的问题。希望我的编辑帮助。 – Kevin 2012-01-20 14:10:22
请注意,-drawInContext:不会在CAShapeLayer中调用。 – 2012-11-06 18:20:03