- (void)drawRect:(CGRect)rect
{
// Drawing code
[super drawRect:rect];
/* Get the graphics context for drawing */
CGContextRef context = UIGraphicsGetCurrentContext();
// NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context."];
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"this is a very very long context.this is a very very long context.this is a very very long context.this is a very very long context.."];
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attrString);
CGMutablePathRef path = CGPathCreateMutable();
CFRange fitRange;
CGSize size = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter,CFRangeMake(0, attrString.length),NULL,self.bounds.size,&fitRange);
NSLog(@"attrString.length = %d",attrString.length);
NSLog(@"fitRange: location = %ld,length = %ld",fitRange.location,fitRange.length);
NSLog(@"size = %@",NSStringFromCGSize(size));
CGPathAddRect(path, NULL, rect);
CGRect imgBounds = CGRectMake(0, size.height, 236, 308);
CGPathAddRect(path, NULL, imgBounds);
NSLog(@"imgBounds:%@",NSStringFromCGRect(imgBounds));
CGContextDrawPath(context,kCGPathFill);
UIImage *image = [UIImage imageNamed:@"aaa.jpg"];
CGContextDrawImage(context, imgBounds, image.CGImage);
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attrString.length), path, NULL);
/* Core Text Coordinate System is OSX style */
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTFrameDraw(frame, context);
}
如果attrString太长。图像的位置将显示错误。我该如何解决这个问题?
if context is long: ----------------------- -contextcontextcontext- -contextcontextcontext- - - - context- - context- - context- - context- - context- - context- -imgcontextcontextcont- -imgcontextcontextcont- ----------------------- if context is not long: ----------------------- -contextcontextcontext- -contextcontextcontext- -img - -img - - - - - - - -----------------------
为什么?