绘图UIGraphicsGetCurrentContext返回为空?

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

// Drawing a rect函数

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

   CGContextRef ctx = UIGraphicsGetCurrentContext();3d

    

    UIGraphicsPushContext(ctx);调试

CGContextAddRect(ctx, rectangle);文档

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

CGContextFillPath(ctx);方法


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

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

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

由于在drawRect以前,系统会往栈里面压入一个valid的CGContextRef,

除非本身去维护一个CGContextRef,不然不该该在其余地方取CGContextRef。】


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

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

二、重写该类的方法

- (void)drawRect:(CGRect)rect

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

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

[self.view addSubview:myview];


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



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

相关文章
相关标签/搜索