I am using Core Text to draw text. I would like to get different execution boundaries, but when I call CTRunGetImageBounds
, the returned rectangle is the right size, but in the wrong place. In particular, the beginning of the line is at the end of the text as a whole.
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
self.transform = CGAffineTransformMakeScale(1.0, -1.0);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
[[UIColor whiteColor] set];
CGContextFillRect(context, self.bounds);
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@"Blue should be underlined."];
NSRange blueRange = NSMakeRange(0, 4);
[attrString beginEditing];
[attrString addAttribute:(NSString *)kCTFontAttributeName value:(id)CTFontCreateWithName((CFStringRef)@"Helvetica", 20.0, NULL) range:NSMakeRange(0, [attrString length])];
[attrString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[[UIColor blueColor] CGColor] range:blueRange];
[attrString addAttribute:(NSString *)kCTUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:blueRange];
[attrString endEditing];
CGMutablePathRef path = CGPathCreateMutable();
CGRect bounds = CGRectMake(10.0, 10.0, 200.0, 200.0);
[[UIColor redColor] set];
CGContextFillRect(context, bounds);
CGPathAddRect(path, NULL, bounds);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CTFrameDraw(frame, context);
for (id lineObj in (NSArray *)CTFrameGetLines(frame)) {
CTLineRef line = (CTLineRef)lineObj;
for (id runObj in (NSArray *)CTLineGetGlyphRuns(line)) {
CTRunRef run = (CTRunRef)runObj;
CGRect runBounds = CTRunGetImageBounds(run, context, CFRangeMake(0, 0));
NSLog(@"bounds: %@", NSStringFromCGRect(runBounds));
[[UIColor greenColor] set];
CGContextFillRect(context, runBounds);
}
}
CFRelease(framesetter);
CFRelease(frame);
[attrString release];
}
It produces:
source
share