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

IOS Quartz2D cannot get image from current context

我错过了什么?卡住了几个小时,drawRect 按预期绘制,从 viewcontoller 调用 getTheImage() UIGraphicsGetImageFromCurrentImageContext() returns 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;
}

You should call this function only when a bitmap-based graphics context is the current graphics context. If the current context is nil or was not created by a call to UIGraphicsBeginImageContext, this function returns nil.

您的通话显然不在上下文中。