Ios 检测分层触摸
我通过覆盖draw rect创建了一个蜘蛛图,我正在使用core grahics CAShapeLayer绘制我的区域,屏幕上创建了多个CAShapeLayer区域,我想检测用户触摸时触摸了哪一层。。。但是我不知道怎么做?首先,您不应该在drawRect中绘制图层,但这不是您的问题。要识别“接触”的图层,可以执行以下操作Ios 检测分层触摸,ios,Ios,我通过覆盖draw rect创建了一个蜘蛛图,我正在使用core grahics CAShapeLayer绘制我的区域,屏幕上创建了多个CAShapeLayer区域,我想检测用户触摸时触摸了哪一层。。。但是我不知道怎么做?首先,您不应该在drawRect中绘制图层,但这不是您的问题。要识别“接触”的图层,可以执行以下操作 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *tou
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInView:self.view];
for (id sublayer in self.view.layer.sublayers) {
BOOL touchInLayer = NO;
if ([sublayer isKindOfClass:[CAShapeLayer class]]) {
CAShapeLayer *shapeLayer = sublayer;
if (CGPathContainsPoint(shapeLayer.path, 0, touchLocation, YES)) {
// This touch is in this shape layer
touchInLayer = YES;
}
} else {
CALayer *layer = sublayer;
if (CGRectContainsPoint(layer.frame, touchLocation)) {
// Touch is in this rectangular layer
touchInLayer = YES;
}
}
}
}
}
迅速回答
这是在触摸开始时开始的,您还可以实现连续跟踪,以防您需要跟踪什么
它是如何工作的,你可以在BeginKing中获得触摸位置,然后检查,你的层框架包含你触摸的点。如果是,它将打印语句。同样的方法,你可以检查你所有的图层
override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let loaction = touch.location(in: self)
//update yourLayer with your layer name
if yourLayer.frame.contains(previousLoaction) {
Print("Touch is inside yourLayer layer")
}
}
嗨,Jody,你能把if条件里面的代码扩展一下吗?好的,我更新了一些细节。基本上,如果它是一个形状层,您可以查询它的路径并查看该路径是否包含点。。。但是请注意,您必须将填充类型作为CGPathContainsPoint的一部分进行传递-我假设为偶数/奇数。使用您需要的任何东西…如果线宽大于1,这不适用于边界上的接触。要考虑任何
。转换层继承权中的s将点转换为路径作为其层的层。路径即(Swift)让p=viewLayer.convertPoint(touchLocation,toLayer:sublayer)
。