CGMutablePathRef меняет цвет - PullRequest
       14

CGMutablePathRef меняет цвет

2 голосов
/ 22 декабря 2011

Я использую пример, который Apple предоставил в одном из своих примеров для рисования CGPath на MKOverlayView. На данный момент линия рисуется одним цветом, но я бы хотел установить ее в разных точках пути.

    - (CGPathRef)newPathForPoints:(MKMapPoint *)points
                   pointCount:(NSUInteger)pointCount
                     clipRect:(MKMapRect)mapRect
                    zoomScale:(MKZoomScale)zoomScale
{
    // The fastest way to draw a path in an MKOverlayView is to simplify the
    // geometry for the screen by eliding points that are too close together
    // and to omit any line segments that do not intersect the clipping rect.  
    // While it is possible to just add all the points and let CoreGraphics 
    // handle clipping and flatness, it is much faster to do it yourself:
    //
    if (pointCount < 2)
        return NULL;

    CGMutablePathRef path = NULL;

    BOOL needsMove = YES;

#define POW2(a) ((a) * (a))

    // Calculate the minimum distance between any two points by figuring out
    // how many map points correspond to MIN_POINT_DELTA of screen points
    // at the current zoomScale.
    double minPointDelta = MIN_POINT_DELTA / zoomScale;
    double c2 = POW2(minPointDelta);

    MKMapPoint point, lastPoint = points[0];
    NSUInteger i;
    for (i = 1; i < pointCount - 1; i++)
    {
        point = points[i];
        double a2b2 = POW2(point.x - lastPoint.x) + POW2(point.y - lastPoint.y);
        if (a2b2 >= c2) {
            if (lineIntersectsRect(point, lastPoint, mapRect))
            {
                if (!path) 
                    path = CGPathCreateMutable();
                if (needsMove)
                {
                    CGPoint lastCGPoint = [self pointForMapPoint:lastPoint];
                    CGPathMoveToPoint(path, NULL, lastCGPoint.x, lastCGPoint.y);
                }
                CGPoint cgPoint = [self pointForMapPoint:point];
                CGPathAddLineToPoint(path, NULL, cgPoint.x, cgPoint.y);
            }
            else
            {
                // discontinuity, lift the pen
                needsMove = YES;
            }
            lastPoint = point;
        }
    }

#undef POW2

    // If the last line segment intersects the mapRect at all, add it unconditionally
    point = points[pointCount - 1];
    if (lineIntersectsRect(lastPoint, point, mapRect))
    {
        if (!path)
            path = CGPathCreateMutable();
        if (needsMove)
        {
            CGPoint lastCGPoint = [self pointForMapPoint:lastPoint];
            CGPathMoveToPoint(path, NULL, lastCGPoint.x, lastCGPoint.y);
        }
        CGPoint cgPoint = [self pointForMapPoint:point];
        CGPathAddLineToPoint(path, NULL, cgPoint.x, cgPoint.y);
    }

    return path;
}

По существу на

CGPathAddLineToPoint(path, NULL, cgPoint.x, cgPoint.y);

line Я хотел бы установить цвет RGB, если это возможно, чтобы он мог быть разного цвета по пути. Я мог бы сделать это на CALayer с контекстом, используя

CGContextSetRGBStrokeColor(ctx, 0, 0, 0, 0.5);

Но я потерян, если это возможно здесь.

1 Ответ

3 голосов
/ 22 декабря 2011

Это невозможно.Цвет обводки является атрибутом контекста, а не пути;контекст использует свой текущий цвет обводки, когда вы обводите весь путь.Нет никакого способа сказать контексту «использовать этот цвет обводки для этого lineto, и этот цвет обводки для этого lineto» и т. Д.

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

...