注意:上面这种方式绘制的图像除了可以显示在界面上还可以调用对应方法进行保存(代码注释中已经包含保存方法);除此之外这种方法相比在drawRect:方法中绘制图形效率更高,它不用每次展示时都调用所有图形绘制方法。
绘制到PDF绘制到PDF则要启用pdf图形上下文,PDF图形上下文的创建使用方式跟位图图形上下文是类似的,需要注意的一点就是绘制内容到PDF时需要创建分页,每页内容的开始都要调用一次IGraphicsBeginPDFPage();方法。下面的示例演示了文本绘制和图片绘制(其他图形绘制也是类似的):
// // KCMainViewController.m // Quartz2D // // Created by Kenshin Cui on 14-3-17. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // #import <CoreText/CoreText.h> #import "KCMainViewController.h" #import "KCView.h" #import "KCView2.h" @interface KCMainViewController () @end @implementation KCMainViewController - (void)viewDidLoad { [super viewDidLoad]; [self drawContentToPdfContext]; } #pragma mark 利用pdf图形上下文绘制内容到pdf文档 -(void)drawContentToPdfContext{ //沙盒路径(也就是我们应用程序文件运行的路径) NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path=[[paths firstObject] stringByAppendingPathComponent:@"myPDF.pdf"]; NSLog(@"%@",path); //启用pdf图形上下文 /** path:保存路径 bounds:pdf文档大小,如果设置为CGRectZero则使用默认值:612*792 pageInfo:页面设置,为nil则不设置任何信息 */ UIGraphicsBeginPDFContextToFile(path,CGRectZero,[NSDictionary dictionaryWithObjectsAndKeys:@"Kenshin Cui",kCGPDFContextAuthor, nil]); //由于pdf文档是分页的,所以首先要创建一页画布供我们绘制 UIGraphicsBeginPDFPage();NSString *title=@"Welcome to Apple Support"; NSMutableParagraphStyle *style=[[NSMutableParagraphStyle alloc]init]; NSTextAlignment align=NSTextAlignmentCenter; style.alignment=align; [title drawInRect:CGRectMake(26, 20, 300, 50) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSParagraphStyleAttributeName:style}]; NSString *content=@"Learn about Apple products, view online manuals, get the latest downloads, and more. Connect with other Apple users, or get service, support, and professional advice from Apple."; NSMutableParagraphStyle *style2=[[NSMutableParagraphStyle alloc]init]; style2.alignment=NSTextAlignmentLeft; // style2.firstLineHeadIndent=20; [content drawInRect:CGRectMake(26, 56, 300, 255) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:[UIColor grayColor],NSParagraphStyleAttributeName:style2}]; UIImage *image=[UIImage imageNamed:@"applecare_folks_tall.png"]; [image drawInRect:CGRectMake(316, 20, 290, 305)]; UIImage *image2=[UIImage imageNamed:@"applecare_page1.png"]; [image2 drawInRect:CGRectMake(6, 320, 600, 281)]; //创建新的一页继续绘制其他内容 UIGraphicsBeginPDFPage(); UIImage *image3=[UIImage imageNamed:@"applecare_page2.png"]; [image3 drawInRect:CGRectMake(6, 20, 600, 629)]; //结束pdf上下文 UIGraphicsEndPDFContext(); } @end生成的pdf文档:

知识补充
1.Core Graphics是基于C语言的一套框架,开发时无法像使用Obj-C一样调用;