iOS 屏幕截图

来源:互联网 发布:淘宝月销量怎么计算 编辑:程序博客网 时间:2024/04/28 07:08
/**  *截图功能  */+(UIImage *)screenShotFromView:(UIView *)view area:(CGRect)rect dstSize:(CGSize)dsize {        UIGraphicsBeginImageContextWithOptions(dsize, YES, 0);        [[view layer] renderInContext:UIGraphicsGetCurrentContext()];        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();        UIGraphicsEndImageContext();        CGImageRef imageRef = viewImage.CGImage;        CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);        UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];        NSData *imageViewData = UIImagePNGRepresentation(sendImage);        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);        NSString *documentsDirectory = [paths objectAtIndex:0];        NSString *pictureName= @"screenShow.png";        NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:pictureName];        //保存照片到沙盒目录    [imageViewData writeToFile:savedImagePath atomically:YES];        CGImageRelease(imageRefRect);        //从手机本地加载图片        UIImage *bgImage2 = [[UIImage alloc]initWithContentsOfFile:savedImagePath];        return bgImage2;}- (void)screenShotFromScrollView:(UIScrollView *)view area:(CGRect)rect dstSize:(CGSize)dsize {        UIImage* image = nil;        UIGraphicsBeginImageContext(view.contentSize);        {                CGPoint savedContentOffset = view.contentOffset;                CGRect savedFrame = view.frame;                view.contentOffset = CGPointZero;                view.frame = CGRectMake(0, 0, view.contentSize.width, view.contentSize.height);       [view.layer renderInContext: UIGraphicsGetCurrentContext()];                image = UIGraphicsGetImageFromCurrentImageContext();                view.contentOffset = savedContentOffset;                view.frame = savedFrame;            }        UIGraphicsEndImageContext();        if (image != nil) {                NSLog(@"截图成功!");            }    }

出现这个错,一般是因为 frame中的高或宽为0或负值。

 <Error>: CGContextSaveGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.


0 0
原创粉丝点击