- (UIImage *)screenshotWithRect:(CGRect)rect
{
UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
if (context == NULL)
{
return nil;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
[self snapshotViewAfterScreenUpdates:YES];
if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
}else
{
[self.layer renderInContext:context];
}
CGContextRestoreGState(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
注意:[self snapshotViewAfterScreenUpdates:YES];
参数:YES-代表视图的属性改变渲染完毕后截屏,NO-代表立刻将当前状态的视图截图
图片转格式
// NSData *imageData = UIImageJPEGRepresentation(image, 1); // convert to jpeg
// image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];
网友评论