// 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]; }