2013-01-21 23 views
0

Possible Duplicate:
Drawing shape iOS
CGContextRef, CGPoint, and CGSize设置使用CGContextRef

我试图用一个电流法,我必须包括CGContextRef,CGPoint和CGSize背景:

CGPoint p1 = {10, 10}; 

CGSize size; 

CGContextRef context = UIGraphicsGetCurrentContext(); 

[self drawArrowWithContext:context atPoint:p1 withSize:size lineWidth:400 arrowHeight:400]; 

当我运行的应用程序,我得到这个错误:

年01月21 21点41分56秒来自Alexs-ipad的防溅它[1497]:CGContextDrawPath:无效的上下文为0x0

的问题必须在康特xt,但我无法在互联网上的任何地方找到问题的解决方案。这整个代码应该调用绘制箭头的方法。 感谢您的帮助。

+0

这是关于同一件事的第三个问题。 –

回答

2

为了返回一个有效的上下文,你必须在适当的区域。

这基本上意味着这段代码需要在drawRect:或者您需要创建一个使用UIGraphicsBeginImageContext

更新的图像内容:在的drawRect:

drawRect:是要求每个UIView的特殊方法为您提供一个访问点,使用Core Graphics进行自定义绘图。最常见的用法是在您的案例中创建一个自定义UIView对象ArrowView。然后,你可以使用你的代码覆盖drawRect:

- (void)drawRect:(CGRect)rect 
{ 
    CGPoint p1 = {10, 10}; 

    CGSize size; 

    CGContextRef context = UIGraphicsGetCurrentContext(); 

    [self drawArrowWithContext:context atPoint:p1 withSize:size lineWidth:400 arrowHeight:400]; 
} 

更新:图像内容

进军定制核心图形绘制次要的方法是创建一个imageContext然后收获的结果。

所以,您首先创建一个图像上下文,运行您的绘图代码,然后将其转换为可添加到现有视图的UIImage。

UIGraphicsBeginImageContext(CGSizeMake(400.0, 400.0)); 

CGPoint p1 = {10, 10}; 

CGSize size; 

CGContextRef context = UIGraphicsGetCurrentContext(); 

[self drawArrowWithContext:context atPoint:p1 withSize:size lineWidth:400 arrowHeight:400]; 

// converts your context into a UIImage 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

// Adds that image into an imageView and sticks it on the screen. 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
[self.view addSubview:imageView]; 
+0

抱歉,但我不明白我需要做什么。箭头必须出现在我的UIview中... – Alessandro

+0

像这样:UIGraphicsBeginImageContext(self.drawImage.frame.size); [drawImage.image drawInRect:CGRectMake(0,0,self.drawImage.frame.size.width,self.drawImage.frame.size.height)]; ?? – Alessandro

+0

我试过这个,但没有办法:CGContextRef currentContext = UIGraphicsGetCurrentContext(); UIGraphicsBeginImageContext(self.view.frame.size); – Alessandro