记得系统会维护一个CGContextRef的栈,UIGraphicsGetCurrentContext()会取出栈顶的context,所以在setFrame调用用UIGraphicsGetCurrentContext(), 但获得的上下文总是nil。百度得知只能在drawRect里调用UIGraphicsGetCurrentContext(),
因为在drawRect之前,系统会往栈里面压入一个valid的CGContextRef,除非自己去维护一个CGContextRef,否则不应该在其他地方取CGContextRef。
那如果就像在drawRect之外获得context怎么办?那只能自己创建位图上下文了:
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0);
CGContextRef context =UIGraphicsGetCurrentContext();
//然后在context上绘画。。。
UIImage *temp = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();