使用coretext绘制字符串布局错误

时间:2013-07-19 06:40:19

标签: ios core-text

我的代码是:

- (void)drawRect:(CGRect)rect {

/* Define some defaults */
float padding = 0.0f;
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef) [UIFont systemFontOfSize:12].fontName, [UIFont systemFontOfSize:12].lineHeight, NULL);

/* Get the graphics context for drawing */
CGContextRef ctx = UIGraphicsGetCurrentContext();

/* Core Text Coordinate System is OSX style */
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);

//CGRect textRect = CGRectMake(padding, padding, self.frame.size.width, self.frame.size.height);
CGRect textRect = CGRectMake(padding, padding, 100, 100);


/* Create a path to draw in and add our text path */
CGMutablePathRef pathToRenderIn = CGPathCreateMutable();
CGPathAddRect(pathToRenderIn, NULL, textRect);
NSLog(@"textRect:%@",NSStringFromCGRect(self.bounds));
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"hello world!"];
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef) attrString, CFRangeMake(0, attrString.length), kCTFontAttributeName, font);

/* Get a framesetter to draw the actual text */
CTFramesetterRef fs = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) attrString);
CTFrameRef frame = CTFramesetterCreateFrame(fs, CFRangeMake(0, attrString.length), pathToRenderIn, NULL);

/* Draw the text */
CTFrameDraw(frame, ctx);

/* Release the stuff we used */
CFRelease(frame);
CFRelease(pathToRenderIn);
CFRelease(fs);

}

然而,看起来像这样: 如何让文本从左上角开始,不要修改文本框架(宽度= 100和高度= 100)?

    xxxxxxxxxxxxx
    x           x
    x           x
    x           x
    x           x
    x           x
    xtext...    x
    x           x
    xxxxxxxxxxxxx

1 个答案:

答案 0 :(得分:0)

只需在代码中更改以下内容:

CGRect textRect = CGRectMake(padding, self.frame.size.height - 100, 100, 100);

无需更改文本rect的帧大小(如您所示),但我们需要更改帧原点的y。