美文网首页iOS开发iOS-Swift
UIGraphicsGetCurrentContext()的使用

UIGraphicsGetCurrentContext()的使用

作者: 执着_7748 | 来源:发表于2018-08-07 10:58 被阅读215次

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();

相关文章

网友评论

    本文标题:UIGraphicsGetCurrentContext()的使用

    本文链接:https://www.haomeiwen.com/subject/juhovftx.html