因为项目中很多地方需要分享截屏截图,所以写了几个截屏方法与大家分享
截屏(按view来截取)
/**
* 截屏-
* isWathermark 是否带有水印-默认带有
* isSave 是否保存到相册-默认保存
* view 截图的view
*/
- (UIImage *)TDScreenCapture_isHaveWatermark:(BOOL)isWatermark isSavePhoto:(BOOL)isSave snapshotView:(UIView *)view
{
// 判断是否为retina屏, 即retina屏绘图时有放大因子
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(view.bounds.size);
}
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 保存到相册
if (isSave) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
//拼接水印
if (isWathermark) {
return [self addImage:image toImage:[UIImage imageNamed:@"yourWaterImg"]];
} else {
return image;
}
}
滚动截图
/**
* 截屏-
* scroll 当前页面,需要截屏的scroll
* isWathermark 是否带有水印-默认带有
* isSave 是否保存到相册-默认保存
*/
- (UIImage *)TDScreen_LongCapture_withScrollView:(UIScrollView *)scroll isHaveWatermark:(BOOL)isWathermark isSavePhoto:(BOOL)isSave
{
UIImage* image = nil;
UIGraphicsBeginImageContextWithOptions(scroll.contentSize, NO, [UIScreen mainScreen].scale);
CGPoint savedContentOffset = scroll.contentOffset;
CGRect savedFrame = scroll.frame;
scroll.contentOffset = CGPointZero;
scroll.frame = CGRectMake(0, 0, scroll.contentSize.width, scroll.contentSize.height);
[scroll.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
scroll.contentOffset = savedContentOffset;
scroll.frame = savedFrame;
UIGraphicsEndImageContext();
// 保存到相册
if (isSave) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
//拼接水印
if (isWathermark) {
return [self addImage:image toImage:[UIImage imageNamed:@"yourWaterImg"]];
} else {
return image;
}
}
把两张图片合成为一张图片
/**
* 拼接图片
* image1 第一张图
* image2 第二张图(在第一张图下面,可自行定义n张图相拼接,自行定义拼接后的尺寸,垂直/水平拼接)
*/
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {
CGFloat width_img_1 = image1.size.width;
CGFloat width_img_2 = image2.size.width;
CGFloat height_img_1 = image1.size.height;
CGFloat height_img_2 = image2.size.height;
CGFloat height_all = image1.size.height + image2.size.height;
CGSize offScreenSize = CGSizeMake(width_img_1, height_all);
//重绘图片
// UIGraphicsBeginImageContext(CGSizeMake(image1.size.width, image1.size.height+image2.size.height));用这个重绘图片会失真
UIGraphicsBeginImageContextWithOptions(offScreenSize, NO, [UIScreen mainScreen].scale);
// Draw image
[image1 drawInRect:CGRectMake(0, 0, width_img_1, height_img_1)];
[image2 drawInRect:CGRectMake(0, height_img_1, width_img_1, height_img_2)];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}