0
- (UIImage*) screenshot
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
    //UIGraphicsBeginImageContext(self.bounds.size);
    PO (NSStringFromCGRect(self.bounds));
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return myImage;
}

It works on all of my UIView. However, if I generate my own UIView in code like this

+(UIImage *) imageAsScreenShotFromLabel:(NSString*) strLabel
{
    UILabel * lbl=[[UILabel alloc]init];
    lbl.text =strLabel;
    [lbl resizeToStretch];
    return lbl.screenshot;
}

It fails and I got this error:

Sep 12 15:41:05 Jupiter.local [70630] <Error>: CGContextSaveGState: invalid context 0x0
Sep 12 15:41:05 Jupiter.local [70630] <Error>: CGContextClipToRect: invalid context 0x0
Sep 12 15:41:05 Jupiter.local [70630] <Error>: CGContextSetAlpha: invalid context 0x0
Sep 12 15:41:05 Jupiter.local [70630] <Error>: CGContextRestoreGState: invalid context 0x0

Why?

4

1 回答 1

-1

根据文档

当前图形上下文默认为 nil。在调用它的 drawRect: 方法之前,视图对象将一个有效的上下文压入堆栈,使其成为当前的。

所以你需要把这段代码放在drawRect方法中

于 2013-09-12T09:00:33.530 回答