图片类型的上下文可以帮我们获取图片,和layer类型的上下文是不一样的,图片类型的上下文渲染是渲染到一张图片上,而layer类型的上下文是直接渲染到了UIView上了。
我们对于图片类型的上下文我们首先要开启,结束之后别忘记关闭。大致的步骤如下所示。
//开启图片类型的上下文
UIGraphicsBeginImageContext(CGSizeMake(300, 300));
//获取当前的上下文(图片类型)
CGContextRef ctx=UIGraphicsGetCurrentContext();
//拼接路径,同时把理解添加到上下文中
CGContextMoveToPoint(ctx, 50, 50);
CGContextAddLineToPoint(ctx, 100, 100);
//渲染
CGContextStrokePath(ctx);
//通过图片类型的上下文去获取图片的对象
UIImage * image=UIGraphicsGetImageFromCurrentImageContext();
//关闭图片类型的上下文
UIGraphicsEndImageContext();
//把获取到的图片放到图片框上
self.imageView.image=image;
把图片保存到沙盒中//获取Document的路径
NSString * documentPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//获取文件的路径
NSString * fliePath=[documentPath stringByAppendingPathComponent:@"hh.png"];
//把image的对象转换成NSData
NSData * data=UIImagePNGRepresentation(image);
//通过data的Write to file方法写到沙盒中
[data writeToFile:fliePath atomically:YES];
NSLog(@"%@",fliePath);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 300), NO, 0);这个参数也可以开始图片的上下文类型,第二个参数是设置透不透明,YES就是为不透明,反之就是透明,第三个参数是缩放的比例,如果我们传0就默认的去用屏幕的缩放因子 [UIScreen mainScreen].scale,。上面的那个获取上下文的方法相当于下面的获取上下文方法的第二个参数为NO,第三个参数为1。
关于UIGraphicsBeginImageContextWithOptions函数,官方文档的解释是
You use this function to configure the drawing environment for rendering into a bitmap. The format for the bitmap is a ARGB 32-bit integer pixel format using host-byte order. If the opaque parameter is YES
, the alpha channel is ignored and the bitmap is treated as fully opaque (kCGImageAlphaNoneSkipFirst
| kCGBitmapByteOrder32Host
). Otherwise, each pixel uses a premultipled ARGB format (kCGImageAlphaPremultipliedFirst
| kCGBitmapByteOrder32Host
).
The environment also uses the default coordinate system for UIKit views, where the origin is in the upper-left corner and the positive axes extend down and to the right of the origin. The supplied scale factor is also applied to the coordinate system and resulting images. The drawing environment is pushed onto the graphics context stack immediately.
While the context created by this function is the current context, you can call the UIGraphicsGetImageFromCurrentImageContext
function to retrieve an image object based on the current contents of the context. When you are done modifying the context, you must call the UIGraphicsEndImageContext
function to clean up the bitmap drawing environment and remove the graphics context from the top of the context stack. You should not use the UIGraphicsPopContext
function to remove this type of context from the stack.
In most other respects, the graphics context created by this function behaves like any other graphics context. You can change the context by pushing and popping other graphics contexts. You can also get the bitmap context using the UIGraphicsGetCurrentContext
function.
This function may be called from any thread of your app.
大致的意思就是