若是想繪製一個矩形,直接將一下代碼拷貝到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