Ios 使用CGContextRef设置上下文

Ios 使用CGContextRef设置上下文,ios,Ios,可能重复: 我尝试使用当前的方法,其中必须包括CGContextRef、CGPoint和CGSize: CGPoint p1 = {10, 10}; CGSize size; CGContextRef context = UIGraphicsGetCurrentContext(); [self drawArrowWithContext:context atPoint:p1 withSize:size lineWidth:400 arrowHeight:400]; 当我运行应用程序时,

可能重复:

我尝试使用当前的方法,其中必须包括CGContextRef、CGPoint和CGSize:

CGPoint p1 = {10, 10};

CGSize size;

CGContextRef context = UIGraphicsGetCurrentContext();

[self drawArrowWithContext:context atPoint:p1 withSize:size lineWidth:400 arrowHeight:400];
当我运行应用程序时,出现以下错误:

Jan 21 21:41:56 Alexs ipad Splash it[1497]:CGContextDrawPath:无效上下文0x0

这个问题一定是背景问题,但我在互联网上找不到解决这个问题的方法。整个代码应该调用一个方法来绘制箭头。
感谢您的帮助。

要返回有效的上下文,您必须位于相应的区域

这基本上意味着此代码需要位于
drawRect:
中,或者需要使用
UIGraphicsBeginImageContext

更新:DrawRect:

drawRect:
是为每个UIView调用的一种特殊方法,它提供了一个访问点,可以使用核心图形进行自定义绘图。最常见的用法是在您的案例中创建自定义UIView对象,即
箭头视图
。然后,您将使用您的代码覆盖
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];

对不起,我不明白我需要做什么。箭头必须出现在我的UIview中…如下所示:UIGraphicsBeginImageContext(self.drawImage.frame.size);[drawImage.image drawInRect:CGRectMake(0,0,self.drawImage.frame.size.width,self.drawImage.frame.size.height)]??我试过了,但没有办法:CGContextRef currentContext=UIGraphicsGetCurrentContext();UIGraphicsBeginImageContext(self.view.frame.size);我用描述每个方法的代码更新了我的答案。这是关于同一件事的第三个问题。