- (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 太长。图片的位置会显示错误。我怎样才能解决这个问题?
如果上下文很长: ---------------------- -上下文上下文上下文- -上下文上下文上下文- - - - 语境- - 语境- - 语境- - 语境- - 语境- - 语境- -imgcontextcontextcont- -imgcontextcontextcont- ---------------------- 如果上下文不长: ---------------------- -上下文上下文上下文- -上下文上下文上下文- -img- -img- - - - - - - ----------------------
为什么 ?