I'm using Core Text to layout text in an UIView but am having troubles with
getting the correct size that the text needs, so I can set the contentSize of
the UIScrollView that it is embedded in. I know it is the wrong size, because
the last line is not showing.
I've done some spitting around, and it seems that
CTFramesetterSuggestFrameSizeWithConstraints may not always work properly.
However I haven't found a solution that works for me.
I've pasted my code below, maybe I am overlooking something?
Thanks,
- Koen.
==============================
// create the string:
NSString *testString = @"This is a not so very long but at least long
enough test string to cover more than one line.";
CFMutableAttributedStringRef attrString =
CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0),
(CFStringRef) testString );
CFIndex stringLength = CFStringGetLength((CFStringRef) attrString);
// give it a font
UIFont* uiFont = [UIFont fontWithName: @"Courier" size: 22.0];
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)
uiFont.fontName, uiFont.pointSize, NULL);
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, stringLength),
kCTFontAttributeName, ctFont);
// calculate the size it occupies
CTFramesetterRef framesetter =
CTFramesetterCreateWithAttributedString(attrString);
CFRange fitRange;
CGSize frameSize =
CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0,
stringLength), NULL, CGSizeMake(self.bounds.size.width, CGFLOAT_MAX),
&fitRange);
self.frame = CGRectMake(0, 0, self.frame.size.width, frameSize.height);
// <<<<==== frameSize.height is too small
// draw the string:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.frame);
CTFramesetterRef framesetter =
CTFramesetterCreateWithAttributedString((CFAttributedStringRef) attrString);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,
stringLength), path, NULL);
CTFrameDraw(frameRef, context);
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]