2011-04-16 140 views
3

我在viewLoad中使用下面的代码(我不想在- (void)drawRect:(CGRect)rect中绘制)以便在视图中添加矩形但不起作用。为什么?问题在绘制矩形

CGRect rect=CGRectMake(10,10,150,140); 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f}; 
CGContextSetStrokeColor(context, red); 
CGContextBeginPath(context); 
CGContextMoveToPoint(context, 10, 10); 
CGContextAddRect(context, rect); 
CGContextStrokePath(context); 
+0

为什么不在drawRect中绘制:? – Jamie 2011-04-16 15:56:29

回答

3

UIGraphicsGetCurrentContext()将在没有当前上下文时返回nil。在调用drawRect:之前为您创建一个上下文;如果要手动创建上下文,请使用UIGraphicsBeginImageContextUIGraphicsBeginImageContextWithOptions启动一个,UIGraphicsGetImageFromCurrentImageContext()以在您完成释放上下文时提取UIImage和UIGraphicsEndImageContext()。详情请参阅the documentation

您当然也可以创建CGBitmapContextRef并直接使用CoreGraphics调用而不是UIKit调用。每种方法都有优点和缺点,主要区别在于默认转换矩阵。

6

只有在绘制上下文时才能绘制。您可以在任何想要创建图像的位置创建图像上下文,也可以在内部绘制drawRect:以绘制您的视图。你不应该在drawRect:之外画出你的看法。

它可能看起来像你正在获得一个上下文,但实际上你不是UIGraphicsGetCurrentContext() returns nil outside of drawRect:(或更准确:它只返回drawRect:内的上下文,或者如果你自己创建并推送了一个图像上下文)。

+0

我以前的评论很愚蠢,没有很好地阅读这个问题。正确答案+1。 – Till 2011-04-16 15:59:32