Подтвердить что ты не робот

Обнаружение попадания при рисовании линий в iOS

Я хотел бы позволить пользователю рисовать кривые таким образом, чтобы ни одна строка не пересекала другую линию или даже сама. Рисование кривых не проблема, и я даже обнаружил, что могу создать путь, который закрыт и по-прежнему довольно похож на линию, отслеживая узлы линии вперед и назад, а затем закрывая путь.

К сожалению, iOS предоставляет только проверку того, содержится ли точка в закрытом пути (containsPoint: и CGPathContainsPoint). К сожалению, пользователь может довольно легко перемещать свой палец достаточно быстро, чтобы сенсорные точки приземлялись по обеим сторонам существующего пути, фактически не содержащиеся в этом пути, поэтому тестирование сенсорных точек довольно бессмысленно.

Я не могу найти никакого "пересечения" метода путей.

Любые другие мысли о том, как выполнить эту задачу?

4b9b3361

Ответ 1

Хорошо, я придумал способ сделать это. Это несовершенно, но я думал, что другие могут захотеть увидеть технику, так как этот вопрос был рассмотрен несколько раз. Метод, который я использовал, привлекает все элементы, подлежащие тестированию, в контекст растрового изображения, а затем рисует новый сегмент прогрессирующей линии в другой растровый контекст. Данные в этих контекстах сравниваются с помощью побитовых операторов, и если обнаружено какое-либо перекрытие, объявляется хитон.

Идея этого метода состоит в том, чтобы протестировать каждый сегмент недавно нарисованной линии по всем ранее нарисованным линиям и даже против более ранних фрагментов одной и той же строки. Другими словами, этот метод будет определять, когда линия пересекает другую линию, а также когда она пересекает себя.

Доступно примерное приложение, демонстрирующее технику: LineSample.zip.

Ядро тестирования удалений выполняется в моем объекте LineView. Вот два ключевых метода:

- (CGContextRef)newBitmapContext {

    // creating b&w bitmaps to do hit testing
    // based on: http://robnapier.net/blog/clipping-cgrect-cgpath-531
    // see "Supported Pixel Formats" in Quartz 2D Programming Guide
    CGContextRef bitmapContext =
    CGBitmapContextCreate(NULL, // data automatically allocated
                          self.bounds.size.width,
                          self.bounds.size.height,
                          8, 
                          self.bounds.size.width,
                          NULL,
                          kCGImageAlphaOnly);
    CGContextSetShouldAntialias(bitmapContext, NO);
    // use CGBitmapContextGetData to get at this data

    return bitmapContext;
}


- (BOOL)line:(Line *)line canExtendToPoint:(CGPoint) newPoint {

    //  Lines are made up of segments that go from node to node. If we want to test for self-crossing, then we can't just test the whole in progress line against the completed line, we actually have to test each segment since one segment of the in progress line may cross another segment of the same line (think of a loop in the line). We also have to avoid checking the first point of the new segment against the last point of the previous segment (which is the same point). Luckily, a line cannot curve back on itself in just one segment (think about it, it takes at least two segments to reach yourself again). This means that we can both test progressive segments and avoid false hits by NOT drawing the last segment of the line into the test! So we will put everything up to the  last segment into the hitProgressLayer, we will put the new segment into the segmentLayer, and then we will test for overlap among those two and the hitTestLayer. Any point that is in all three layers will indicate a hit, otherwise we are OK.

    if (line.failed) {
        // shortcut in case a failed line is retested
        return NO;
    }
    BOOL ok = YES; // thinking positively

    // set up a context to hold the new segment and stroke it in
    CGContextRef segmentContext = [self newBitmapContext];
    CGContextSetLineWidth(segmentContext, 2); // bit thicker to facilitate hits
    CGPoint lastPoint = [[[line nodes] lastObject] point];
    CGContextMoveToPoint(segmentContext, lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(segmentContext, newPoint.x, newPoint.y);
    CGContextStrokePath(segmentContext);

    // now we actually test
    // based on code from benzado: http://stackoverflow.com/info/6515885/how-to-do-comparisons-of-bitmaps-in-ios/6515999#6515999
    unsigned char *completedData = CGBitmapContextGetData(hitCompletedContext);
    unsigned char *progressData = CGBitmapContextGetData(hitProgressContext);
    unsigned char *segmentData = CGBitmapContextGetData(segmentContext);

    size_t bytesPerRow = CGBitmapContextGetBytesPerRow(segmentContext);
    size_t height = CGBitmapContextGetHeight(segmentContext);
    size_t len = bytesPerRow * height;

    for (int i = 0; i < len; i++) {
        if ((completedData[i] | progressData[i]) & segmentData[i]) { 
            ok = NO; 
            break; 
        }
    }

    CGContextRelease(segmentContext);

    if (ok) {
        // now that we know we are good to go, 
        // we will add the last segment onto the hitProgressLayer
        int numberOfSegments = [[line nodes] count] - 1;
        if (numberOfSegments > 0) {
            // but only if there is a segment there!
            CGPoint secondToLastPoint = [[[line nodes] objectAtIndex:numberOfSegments-1] point];
            CGContextSetLineWidth(hitProgressContext, 1); // but thinner
            CGContextMoveToPoint(hitProgressContext, secondToLastPoint.x, secondToLastPoint.y);
            CGContextAddLineToPoint(hitProgressContext, lastPoint.x, lastPoint.y);
            CGContextStrokePath(hitProgressContext);
        }
    } else {
        line.failed = YES;
        [linesFailed addObject:line];
    }
    return ok;
}

Мне бы хотелось услышать предложения или увидеть улучшения. Во-первых, было бы намного быстрее проверять ограничивающий прямоугольник нового сегмента вместо всего представления.