iOS - 获取大小为UIScrollView可见区域的屏幕截图

时间:2016-04-06 11:27:11

标签: ios objective-c uiscrollview

我找到了question,答案很完美。但是,如果我想要这样设置大小呢?如何为此更改scrollView.contentOffset

例如,我想这样称呼它:

#define multiplier 3.0f

CGSize size = CGSizeMake(scrollView.frame.size.width*multiplier, scrollView.frame.size.height*multiplier); 
UIImage *backgroungImage = [self renderScrollViewToImageWith:scrollView size:size];

-(UIImage *)renderScrollViewToImageWith:(UIScrollView *)_scrollView size:(CGSize)size
{
    UIScrollView *contentScrollView = _scrollView;

    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);

    //what do I do here???
    CGPoint offset = contentScrollView.contentOffset;
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y); <-- what do I do here?

    [contentScrollView drawViewHierarchyInRect:CGRectMake(0, 0, size.width, size.height) afterScreenUpdates:YES];
    UIImage *visibleScrollViewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return visibleScrollViewImage;
}

1 个答案:

答案 0 :(得分:0)

试试这个

CGRect croppingRect = viewToTakeScreenShot.bounds;

UIGraphicsBeginImageContextWithOptions(croppingRect.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
if (context == NULL) return nil;
CGContextTranslateCTM(context, -croppingRect.origin.x, -croppingRect.origin.y);

[viewToTakeScreenShot layoutIfNeeded];
[viewToTakeScreenShot.layer renderInContext:context];

UIImage *screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

试试这个。它可以帮到你。