为了返回一个有效的上下文,你必须在适当的区域。
这基本上意味着这段代码需要在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];
这是关于同一件事的第三个问题。 –