1.截取制定范围(非长图)
- (UIImage *)screenShotWithSize(CGSize *)size {
UIImage* image = nil;
/*
*UIGraphicsBeginImageContextWithOptions有三个参数
*size bitmap上下文的大小,就是生成图片的size
*opaque 是否不透明,当指定为YES的时候图片的质量会比较好
*scale 缩放比例,指定为0.0表示使用手机主屏幕的缩放比例
*/
UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
//此处我截取的是TableView的header.
[self.tableHeaderView.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (image != nil) {
return image;
}else {
return nil;
}
}
2.截取长图,如TableView,CollectionView
- (UIImage *)screenShot {
UIImage* image = nil;
UIGraphicsBeginImageContextWithOptions(self.collectionView.contentSize, YES, 0.0);
//保存collectionView当前的偏移量
CGPoint savedContentOffset = self.collectionView.contentOffset;
CGRect saveFrame = self.collectionView.frame;
//将collectionView的偏移量设置为(0,0)
self.collectionView.contentOffset = CGPointZero;
self.collectionView.frame = CGRectMake(0, 0, self.collectionView.contentSize.width, self.collectionView.contentSize.height);
//在当前上下文中渲染出collectionView
[self.collectionView.layer renderInContext: UIGraphicsGetCurrentContext()];
//截取当前上下文生成Image
image = UIGraphicsGetImageFromCurrentImageContext();
//恢复collectionView的偏移量
self.collectionView.contentOffset = savedContentOffset;
self.collectionView.frame = saveFrame;
UIGraphicsEndImageContext();
if (image != nil) {
return image;
}else {
return nil;
}
}
3.图片拼接
将两张图片拼接在一起,第二张图片拼接在第一张图的下面。
/*masterImage 主图片,生成的图片的宽度为masterImage的宽度
*slaveImage 从图片,拼接在masterImage的下面
*/
- (UIImage *)addSlaveImage:(UIImage *)slaveImage toMasterImage:(UIImage *)masterImage {
CGSize size;
size.width = masterImage.size.width;
size.height = masterImage.size.height + slaveImage.size.height;
UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
//Draw masterImage
[masterImage drawInRect:CGRectMake(0, 0, masterImage.size.width, masterImage.size.height)];
//Draw slaveImage
[slaveImage drawInRect:CGRectMake(0, masterImage.size.height, masterImage.size.width, slaveImage.size.height)];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}