IOS Quartz2D无法从当前上下文获取图像

IOS Quartz2D无法从当前上下文获取图像,ios,objective-c,quartz-2d,Ios,Objective C,Quartz 2d,我错过了什么?已停滞数小时,drawRect按预期绘制,从viewcontoller调用getTheImage(),UIGraphicsGetImageFromCurrentImageContext()返回nil;尝试了许多变化。 感谢您的帮助 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { } return self; } - (void)d

我错过了什么?已停滞数小时,drawRect按预期绘制,从viewcontoller调用getTheImage(),UIGraphicsGetImageFromCurrentImageContext()返回nil;尝试了许多变化。 感谢您的帮助

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextSetLineWidth(context, 5.0);
    CGContextSetStrokeColorWithColor(context, [[UIColor    blackColor]CGColor]);
    CGContextMoveToPoint(context,100.0,100.0);
    CGContextAddLineToPoint(context,200.0,200.0);
    CGContextMoveToPoint(context,200.0,200.0);
    CGContextAddLineToPoint(context,200.0,400.0);
    CGContextStrokePath(context);
}


-(UIImage *)getTheImage
{
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
    NSLog(@"drawImage %@",drawImage);
    return drawImage;
}
你能试试这个吗

-(UIImage *)getTheImage
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"drawImage %@",drawImage);
    return drawImage;
}
仅当基于位图的图形上下文是当前图形上下文时,才应调用此函数。如果当前上下文为nil或不是通过调用UIGraphicsBeginImageContext创建的,则此函数返回nil


显然,您的呼叫不在上下文中。

感谢您的回复,UIGraphicsBeginImageContext仍不起作用,仅接受1个参数。已将UIGraphicsBeginImageContext更改为UIGraphicsBeginImageContextWithOptions,对于UIGraphicsBeginImageContextWithOptions,仍然没有GO问题。你能告诉我你从哪里调用这个getTheImage方法吗?我从视图控制器的VIEWWILLEANCE和VIEWDIDDEANCE方法中调用了此方法,并且从这两个位置图像都不是零。然而,当我从viewDidLoad调用此方法时,图像为零。您应该在视图完全加载后才调用getTheImage方法。您好,我在按下按钮时调用getTheImage(),以将其保存在documents目录中。对于我来说,我发布的上述代码片段正在工作。我通过点击一个按钮调用这个代码来检查它。然后它也开始工作了。你能发布更多的细节吗?