Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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