Search code examples
ioscore-graphicscgpath

CGPathCreateCopyByStrokingPath equivalent on iOS4?


I found CGPathCreateCopyByStrokingPath on iOS 5.0 quite convenient to use but it is available on iOS 5 and later.

Is there any simple way to achieve the same path copying on iOS 4?


Solution

  • I use this, which is compatible across IOS5 and IOS4+. It works 100% if you use the same fill + stroke color. Apple's docs are a little shady about this - they say "it works if you fill it", they don't say "it goes a bit wrong if you stroke it" - but it seems to go slightly wrong in that case. YMMV.

    // pathFrameRange: you have to provide something "at least big enough to 
    // hold the original path"
    
    static inline CGPathRef CGPathCreateCopyByStrokingPathAllVersionsOfIOS( CGPathRef 
      incomingPathRef, CGSize pathFrameRange, const CGAffineTransform* transform,
      CGFloat lineWidth, CGLineCap lineCap, CGLineJoin lineJoin, CGFloat miterLimit )
    {
        CGPathRef result;
    
        if( CGPathCreateCopyByStrokingPath != NULL )
        {
            /**
            REQUIRES IOS5!!!
             */
            result = CGPathCreateCopyByStrokingPath( incomingPathRef, transform,
                lineWidth, lineCap, lineJoin, miterLimit);
        }
        else
        {
            CGSize sizeOfContext = pathFrameRange;
            UIGraphicsBeginImageContext( sizeOfContext );
            CGContextRef c = UIGraphicsGetCurrentContext();
            CGContextSetLineWidth(c, lineWidth);
            CGContextSetLineCap(c, lineCap);
            CGContextSetLineJoin(c, lineJoin);
            CGContextSetMiterLimit(c, miterLimit);
            CGContextAddPath(c, incomingPathRef);
            CGContextSetLineWidth(c, lineWidth);
            CGContextReplacePathWithStrokedPath(c);
            result = CGContextCopyPath(c);
            UIGraphicsEndImageContext();
        }
    }