我的代码是:
- (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 xx xx xx xx xx xtext... x xx xxxxxxxxxxxxx