截取全屏
- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
/**
1.第一个参数表示区域大小
2.第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES
3.第三个参数就是屏幕密度了,关键就是第三个参数 [UIScreen mainScreen].scale
*/
UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
//渲染view.layer
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//保存图片到照片库
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
return image;
}
//方法解释:
void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
size——同UIGraphicsBeginImageContext
opaque—透明开关,如果图形完全不用透明,设置为YES以优化位图的存储。
scale—–缩放因子 iPhone 4是2.0,其他是1.0。虽然这里可以用[UIScreen mainScreen].scale来获取,但实际上设为0后,系统就会自动设置正确的比例了。
根据自定义尺寸截屏
CGRect snapshotFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
UIEdgeInsets snapshotEdgeInsets = UIEdgeInsetsZero;
/**
snapshotFrame 想要截取屏幕的frame
*/
- (UIImage *)snapshotViewFromRect:(CGRect)rect withCapInsets:(UIEdgeInsets)capInsets {
UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, - CGRectGetMinX(rect), - CGRectGetMinY(rect));
[self.view.layer renderInContext:currentContext];
UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *snapshotView = [[UIImageView alloc] initWithFrame:rect];
snapshotView.image = [snapshotImage resizableImageWithCapInsets:capInsets];
//保存图片到照片库
UIImageWriteToSavedPhotosAlbum(snapshotView.image, nil, nil, nil);
return snapshotView.image;
}
网友评论