检测CAShapeLayer触摸

检测CAShapeLayer触摸

本文介绍了检测CAShapeLayer触摸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过覆盖draw rect创建了一个蜘蛛图表,我使用核心grahics CAShapeLayer绘制我的区域,在屏幕上创建了多个CAShapeLayer区域,我想检测用户触摸时触摸的是哪个图层。 ..但我无法弄清楚如何?

I have created a spider chart by overiding draw rect, I am using core grahics CAShapeLayer to draw my areas, there are multiple CAShapeLayer regions which are created on the screen, I want to detect which layer is touched when the users touches... but I can't figure out how?

推荐答案

首先,你不应该在drawRect中绘制图层,但那是不是你的问题。要识别触摸的图层,您可以执行以下操作...

First, you should not be drawing layers in drawRect, but that is not your question. To identify a layer that is "touched" you can do something like this...

- (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;
                }
            }
        }
    }
}

这篇关于检测CAShapeLayer触摸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:56