您的位置:首页 > 移动开发 > IOS开发

iOS QuartzCore - 2D绘图

2016-02-23 16:59 489 查看
图形上下文(Graphics Context):CGContextRef类型的数据,保存绘图信息、绘图状态

绘图流程: 绘制好的图形先保存到图形上下文,后显示到输出目标

一、使用步骤

1.绘图

UIGraphicsBeginImageContextWithOptions( CGSizeMake(200, 200), NO, 0);

//1.获取bitmap上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

//2.绘图(画一个圆)

CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 100, 100));

//3.渲染

CGContextStrokePath(ctx);

//4.获取生成的图片

UIImage *image=UIGraphicsGetImageFromCurrentImageContext();

//5.显示生成的图片到imageview

self.iv.image=image;

//6.保存绘制好的图片到文件中

//先将图片转换为二进制数据,然后再将图片写到文件中

NSData *data=UIImagePNGRepresentation(image);

[data writeToFile:@”/Users/apple/Desktop/abc.png” atomically:YES];

2.自定义UIImageView控件

(1)在自定义类的实现中,重写DrawRect:方法绘制并渲染图形

//重写drawRect:方法

- (void)drawRect:(CGRect)rect

{

[self.image drawInRect:rect];

}

(2)自定义UIImageView

//1.创建

//2.设置图片

//3.设置frame

//4.把创建的自定义的view添加到界面上

SLimageView *iv=[[SLimageView alloc]init];

iv.image=[UIImage imageNamed:@”me”];

iv.frame=CGRectMake(100, 100, 100, 100);

[self.view addSubview:iv];

3.截屏

//延迟两秒保存

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

//获取图形上下文

// UIGraphicsBeginImageContext(self.view.frame.size);

UIGraphicsBeginImageContext(self.contentView.frame.size);

//将view绘制到图形上下文中

//    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
[self.contentView.layer renderInContext:UIGraphicsGetCurrentContext()];

//将截屏保存到相册
UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
UIImageWriteToSavedPhotosAlbum(newImage,self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
});


二、基本属性

三、代码示例

四、总结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: