方法一:View的大小不大于手机屏幕
#pragma mark - 方法一:View的大小不大于手机屏幕
- (UIImage *)GetmakeImageWithView:(UIView *)view andWithSize:(CGSize)size
{
// 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了,关键就是第三个参数 [UIScreen mainScreen].scale。
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
方法二:View的大小大于手机屏幕
#pragma mark - 方法二:View的大小大于手机屏幕
- (UIImage *) snapshotWithScrollView:(UIScrollView *)scrollView
{
UIImage * image = nil;
UIGraphicsBeginImageContext(scrollView.contentSize);
CGPoint savedContentOffset = scrollView.contentOffset;
CGRect savedFrame = scrollView.frame;
scrollView.contentOffset = CGPointZero;
scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
[scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
scrollView.contentOffset = savedContentOffset;
scrollView.frame = savedFrame;
UIGraphicsEndImageContext();
if (image != nil) {
return image;
}
return nil;
}
截取view中某个区域生成一张图片
#pragma mark - 截取view中某个区域生成一张图片
- (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope
{
CGImageRef imageRef = CGImageCreateWithImageInRect([self GetmakeImageWithView:view andWithSize:view.bounds.size].CGImage, scope);
UIGraphicsBeginImageContext(scope.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
CGContextTranslateCTM(context, 0, rect.size.height);//下移
CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
CGContextDrawImage(context, rect, imageRef);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(imageRef);
return image;
}
网友评论