春水初生,春林初盛,春风十里,不如你。
前言
在开发过程中,不免遇到屏幕截图分享,截图添加水印等。本文就记录一下自己项目中分享截图时写的代码,小白们可以参考一下,大神们请绕行。
- 屏幕截图
UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT), NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:ctx];
// 这个就是截图
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
- 添加水印
// 画水印 rect:水印图片相对于截图的位置
- (UIImage *)originImage:(UIImage *)originImage withWaterMask:(UIImage *)mask inRect:(CGRect)rect {
UIGraphicsBeginImageContextWithOptions(originImage.size, NO, 0); // 0.0 for scale means "scale for device's main screen".
//原图
[originImage drawInRect:CGRectMake(0, 0, originImage.size.width, originImage.size.height)];
//水印图
[mask drawInRect:rect];
UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newPic;
}
- 截取scrollView或者tableView长图
UIImage* viewImage = nil;
UITableView *scrollView = self.tableView;
//我把contentSize.height加了一个值,是因为我要在长图底部添加图片
UIGraphicsBeginImageContextWithOptions(CGSizeMake(scrollView.contentSize.width, scrollView.contentSize.height + kRelativeHeight(121)), scrollView.opaque, 0.0);
//记录用户点击分享时视图的偏移量、位置
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()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
//恢复到用户点击时的状态
scrollView.contentOffset = savedContentOffset;
scrollView.frame = savedFrame;
UIGraphicsEndImageContext();