绘图UIGraphicsGetCurrentContext返回为空?

如果想绘制一个矩形,直接将一下代码拷贝到ViewDidLoad中是无效的:

// Drawing a rect

    CGRect rectangle = CGRectMake(10, 10, 120, 25);

   CGContextRef ctx = UIGraphicsGetCurrentContext();

    

    UIGraphicsPushContext(ctx);

CGContextAddRect(ctx, rectangle);

CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);

CGContextFillPath(ctx);


调试发现UIGraphicsGetCurrentContext()函数返回为nil

【按照文档中的说法,系统会维护一个CGContextRef的栈,而UIGraphicsGetCurrentContext()会取栈顶的CGContextRef,

正确的做法是只在drawRect里调用UIGraphicsGetCurrentContext(),

因为在drawRect之前,系统会往栈里面压入一个valid的CGContextRef,

除非自己去维护一个CGContextRef,否则不应该在其他地方取CGContextRef。】


根据以上分析,正确做法:

1、自定义一个类MyView,UIView的子类

2、重写该类的方法

- (void)drawRect:(CGRect)rect

3、将绘制图形的代码拷贝到drawRect方法中
4、在ViewController中的ViewDidLoad中添加该视图,代码如下:

MyView *myview = [[MyView alloc]initWithFrame:self.view.frame];

[self.view addSubview:myview];


5、运行后,界面上出现红色矩形!



其中,不需要导入framework,默认框架已经引入了CoreGraphics.framework




你可能感兴趣的:(绘图UIGraphicsGetCurrentContext返回为空?)