iOS图像处理(8)在PDF中绘图

来源:互联网 发布:复杂网络模型 编辑:程序博客网 时间:2024/04/30 21:20

转载自:http://www.cnblogs.com/zanglitao/p/4037447.html


绘制到PDF则要启用pdf图形上下文,PDF图形上下文的创建使用方式跟位图图形上下文是类似的,需要注意的一点就是绘制内容到PDF时需要创建分页,每页内容的开始都要调用一次UIGraphicsBeginPDFPage方法。下面的示例演示了文本绘制和图片绘制(其他图形绘制也是类似的):

复制代码
- (void)viewDidLoad{    [super viewDidLoad];    //沙盒路径    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);    NSString *path=[[pathArray firstObject] stringByAppendingPathComponent:@"myPDF.pdf"];        //path:保存路径    //bounds:pdf文档大小,如果设置为CGRectZero则使用默认值:612*792    //pageInfo:页面设置,为nil则不设置任何信息    UIGraphicsBeginPDFContextToFile(path, CGRectZero, @{kCGPDFContextAuthor:@"zlt"});    //也可以存储到NSMutableData中    //UIGraphicsBeginPDFContextToData(<#NSMutableData *data#>, <#CGRect bounds#>, <#NSDictionary *documentInfo#>);        //开始第一页绘制    UIGraphicsBeginPDFPage();        NSString *title = @"Welcome to Apple Support";    //段落样式    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];    //对齐方式    NSTextAlignment aligment = NSTextAlignmentCenter;    style.alignment = aligment;    [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;    [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();}
复制代码

 

生成的pdf文档:

 

 

知识补充

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

2.在Quartz 2D中凡是使用带有“Create”或者“Copy”关键字方法创建的对象,在使用后一定要使用对应的方法释放(由于这个框架基于C语言编写无法自动释放内存);

3.Quartz 2D是跨平台的,因此其中的方法中不能使用UIKit中的对象(UIKit只有iOS可用),例如用到的颜色只能用CGColorRef而不能用UIColor,但是UIKit中提供了对应的转换方法;

4.在C语言中枚举一般以“k”开头,由于Quartz 2D基于C语言开发,所以它也不例外(参数中很多枚举都是k开头的);

5.由于Quartz 2D是Core Graphics的一部分,所以API多数以CG开头;

6.在使用Quartz 2D绘图API中所有以“Ref”结尾对象,在声明时都不必声明为指针类型;

7.在使用Quartz 2D绘图API时,凡是“UI”开头的相关绘图函数,都是UIKit对Core Graphics的封装(主要为了简化绘图操作);


0 0