只需要在UIImage的分类中添加一个方法即可
//view: 把需要截图的 控件 传进来
+ (instancetype)captureWithView:(UIView *)view {
//1.开启上下文
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0);
//2.将控制器view的layer渲染到上下文
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
//3.取出图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//4.结束上下文
UIGraphicsEndImageContext();
return newImage;
}
对UIScrollView截图
- (UIImage *)captureScrollView:(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;
}
调用
UIImage *newImage = [UIImage captureWithView:self.view];