最近要做‘截长图分享’,需要将view上显示的所有内容转换成image。查找资料做了,但是获取的图片只显示一部分,下面是代码,大神给看看:
-(UIImage*)getLongShotsImageView:(UIScrollView*)scrollview
{
NSMutableArray *imgArray = [[[NSMutableArray alloc]initWithCapacity:0] autorelease];
NSInteger total = ceilf(scrollview.contentSize.height/scrollview.frame.size.height);
CGSize size = CGSizeZero;
for (NSInteger i = 0; i < total; ++i)
{
[scrollview setContentOffset:CGPointMake(0, i*scrollview.frame.size.height)]
;
if (i == total-1) {
size = CGSizeMake(self.view.frame.size.width, scrollview.contentSize.height- i*scrollview.frame.size.height);
} else {
size = scrollview.frame.size;
}
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, -scrollview.frame.origin.x, -scrollview.frame.origin.y);
[scrollview.layer renderInContext:context];
CGContextRestoreGState(context);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
[imgArray addObject:img];
UIGraphicsEndImageContext();
}
// 拼接
UIImage *image = imgArray[0];
if (imgArray.count == 1) {
return image;
}
for (NSInteger i = 1; i < imgArray.count; i++)
{
image = [self combineWithTopImage:image BottomImage:imgArray[i] ImageSacle:[UIScreen mainScreen].scale];
if (i == imgArray.count-1) {
break;
}
}
return image;
}
- (UIImage *)combineWithTopImage:(UIImage*)image1 BottomImage:(UIImage*)image2 ImageSacle:(CGFloat)imageSacle
{
CGFloat w = image1.size.width;
CGFloat h = image1.size.height + image2.size.height;
CGSize offSize = CGSizeMake(w, h);
UIGraphicsBeginImageContextWithOptions(offSize, NO, imageSacle);
CGRect rect1 = CGRectMake(0, 0, w, image1.size.height);
[image1 drawInRect:rect1];
CGRect rect2 = CGRectMake(0, rect1.origin.y+image1.size.height, w, image2.size.height);
[image2 drawInRect:rect2];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
图:
天蓬老师2017-04-18 09:44:01
You put
CGContextTranslateCTM(context, -scrollview.frame.origin.x, -scrollview.frame.origin.y);
changed to
CGContextTranslateCTM(context, -scrollview.contentOffset.x, -scrollview.contentOffset.y);