UIGraphicsGetCurrentContext一般是使用在drawrect,系統(tǒng)會(huì)維護(hù)一個(gè)CGContextRef的棧,UIGraphicsGetCurrentContext()會(huì)取出棧頂?shù)腸ontext,所以在其他地方調(diào)用該函數(shù),獲取到的上下文都是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,可以自己在創(chuàng)建位圖上下文
這是系統(tǒng)自帶的開始和結(jié)束方法,在繪制之前調(diào)用
// 給出一個(gè)繪制控件的大小
UIGraphicsBeginImageContext(CGSize size);
或者
// 給出一個(gè)繪制控件的大小,以及透明度
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
// 之后就可以在contextRef進(jìn)行繪畫
CGContextRef contextRef =UIGraphicsGetCurrentContext();
// UIGraphicsGetImageFromCurrentImageContext();
// 結(jié)束之后記得加上
UIGraphicsEndImageContext();