使用CoreText排版,取得文字区域精确大小

来源:互联网 发布:mac 多个全屏切换 编辑:程序博客网 时间:2024/05/19 13:23

转载于:http://ikevin.tw/209


在iOS中,要計算文字區域的大小,說實在的是有一點麻煩,因為還沒繪製文字之前,是很難得到文字的區域大小的,所以我們通常的做法是:
1.先開一個極大的區域,固定寬度,然後文字往下排。
2.設定文字大小及行距。
3.取得行數。
4.取得文字區域高度=行數X(文字大小+行距)-行距。 //註:最後一行沒有行距
5.開一個繪圖(context)大小(文字區域寬高)。
6.開始繪圖。
7.取得繪圖內容(UIImage)。

請參考以下範例

// Implement loadView to create a view hierarchy programmatically, without using a nib.- (void)loadView{    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 20, 768, 1004)];    self.view=view;    [self drawTexttoImage];} -(void)drawTexttoImage{    CGRect colRect=CGRectMake(0, 0, 354, 32767);     CGMutablePathRef path = CGPathCreateMutable();    CGPathAddRect(path, NULL, colRect)NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"可以放多一點文字試試看"]//設定字型及大小    CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"STHeitiTC-Medium",24.0f, NULL);    [string addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)fontRef range:NSMakeRange(0, [string length])]//設定對齊方式    CTTextAlignment alignment = kCTJustifiedTextAlignment;     CTParagraphStyleSetting alignmentStyle;    alignmentStyle.spec=kCTParagraphStyleSpecifierAlignment;    alignmentStyle.valueSize=sizeof(alignment);    alignmentStyle.value=&alignment;     //設定行距    CGFloat lineSpace=12.0f;    CTParagraphStyleSetting lineSpaceStyle;    lineSpaceStyle.spec=kCTParagraphStyleSpecifierLineSpacing;    lineSpaceStyle.valueSize=sizeof(24.0f);    lineSpaceStyle.value=&lineSpace;     CTParagraphStyleSetting settings[]={        alignmentStyle,lineSpaceStyle    };     CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings))//設定段落樣式    [string addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)paragraphStyle range:NSMakeRange(0, [string length])];     CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [string length]), path, NULL)NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame)int area_h=[lines count]*(24+12)-12; //計算本文高度      CGRect imageSize=CGRectMake(0, 0, 354, area_h);//設定繪圖區域     UIGraphicsBeginImageContext(imageSize.size);     CGContextRef context=UIGraphicsGetCurrentContext();     CGContextSetTextMatrix(context, CGAffineTransformIdentity);    CGContextTranslateCTM(context, 0, colRect.size.height);    CGContextScaleCTM(context, 1.0, -1.0);     CTFrameDraw(frame, context);        CFRelease(path);    CFRelease(framesetter);    CFRelease(fontRef)//取出圖像及圖像尺寸    [self setImage:UIGraphicsGetImageFromCurrentImageContext() size:imageSize.size]}-(void)setImage:(UIImage *)img size:(CGSize)size{    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width,size.height)];    [imageView setImage:img];    [self.view addSubview:imageView]}
原创粉丝点击