UIGraphicsGetCurrentContext()的使用

UIGraphicsGetCurrentContext一般是使用在drawrect,系统会维护一个CGContextRef的栈,UIGraphicsGetCurrentContext()会取出栈顶的context,所以在其他地方调用该函数,获取到的上下文都是nil

// UIImage context

// The following methods will only return a 8-bit per channel context in the DeviceRGB color space.
// Any new bitmap drawing code is encouraged to use UIGraphicsImageRenderer in leiu of this API.
UIKIT_EXTERN void     UIGraphicsBeginImageContext(CGSize size);
UIKIT_EXTERN void     UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) NS_AVAILABLE_IOS(4_0);
UIKIT_EXTERN UIImage* __nullable UIGraphicsGetImageFromCurrentImageContext(void);
UIKIT_EXTERN void     UIGraphicsEndImageContext(void); 

如果想在drawRect外获取context,可以自己在创建位图上下文
这是系统自带的开始和结束方法,在绘制之前调用

// 给出一个绘制控件的大小
UIGraphicsBeginImageContext(CGSize size);
或者
// 给出一个绘制控件的大小,以及透明度
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);

// 之后就可以在contextRef进行绘画
CGContextRef contextRef =UIGraphicsGetCurrentContext();
// UIGraphicsGetImageFromCurrentImageContext();

// 结束之后记得加上
UIGraphicsEndImageContext();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容