Skip to content

Instantly share code, notes, and snippets.

@uchuugaka
Forked from wess/gist:3136429
Created November 29, 2012 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uchuugaka/4169855 to your computer and use it in GitHub Desktop.
Save uchuugaka/4169855 to your computer and use it in GitHub Desktop.
Get a clipping rect for CoreText
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment