Skip to content

Instantly share code, notes, and snippets.

@wess
Created July 18, 2012 14:14
Show Gist options
  • Select an option

  • Save wess/3136429 to your computer and use it in GitHub Desktop.

Select an option

Save wess/3136429 to your computer and use it in GitHub Desktop.

Revisions

  1. wess created this gist Jul 18, 2012.
    46 changes: 46 additions & 0 deletions gistfile1.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    static CGRect clipRectToPath(CGRect rect, CGPathRef path)
    {
    size_t width = floorf(rect.size.width);
    size_t height = floorf(rect.size.height);
    uint8_t *points = calloc(width * height, sizeof(*points));
    CGContextRef bitmapContext = CGBitmapContextCreate(points, width, height, sizeof(*points) * 8, width, NULL, kCGImageAlphaOnly);
    BOOL atStart = NO;
    NSRange range = NSMakeRange(0, 0);
    NSUInteger x = 0;

    CGContextSetShouldAntialias(bitmapContext, NO);
    CGContextTranslateCTM(bitmapContext, -rect.origin.x, -rect.origin.y);
    CGContextAddPath(bitmapContext, path);
    CGContextFillPath(bitmapContext);

    for (; x < width; ++x)
    {
    BOOL isCol = YES;
    for (int i = 0; i < height; ++i)
    {
    if (points[(i * width + x)] < 128)
    {
    isCol = NO;
    break;
    }
    }

    if (isCol && !atStart)
    {
    atStart = YES;
    range.location = x;
    }
    else if (!isCol && atStart)
    {
    break;
    }
    }

    if (atStart)
    range.length = x - range.location - 1;

    CGContextRelease(bitmapContext);
    free(points);

    return CGRectMake(rect.origin.x + range.location, rect.origin.y, range.length, rect.size.height);
    }