使用额外宽度或高度的iOS Swift截屏

时间:2015-07-24 17:25:23

标签: ios swift uiscrollview

我目前正在将UIScrollView的屏幕截图作为应用功能的一部分。但我想截取包括从底部增加高度的截图。 (UIScrollView中+的UIImageView)

enter image description here

这就是我现在如何使用UIScrollView截图。

UIGraphicsBeginImageContextWithOptions(ScrollView.bounds.size, true, UIScreen.mainScreen().scale)

        let offset = ScrollView.contentOffset

        CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y)

        ScrollView.layer.renderInContext(UIGraphicsGetCurrentContext())

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

1 个答案:

答案 0 :(得分:1)

您可以实现此目的:

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

您的view参数应该是内容视图。

或者您可以拍摄2张照片,其中一张是ScrollView,另一张来自ImageView并合并为一张:

- (UIImage*)imageByCombiningImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
    UIImage *image = nil;

    CGSize newImageSize = CGSizeMake(MAX(firstImage.size.width, secondImage.size.width), MAX(firstImage.size.height, secondImage.size.height));
    if (UIGraphicsBeginImageContextWithOptions != NULL) {
        UIGraphicsBeginImageContextWithOptions(newImageSize, NO, [[UIScreen mainScreen] scale]);
    } else {
        UIGraphicsBeginImageContext(newImageSize); 
    }
    [firstImage drawAtPoint:CGPointMake(roundf((newImageSize.width-firstImage.size.width)/2), 
                                        roundf((newImageSize.height-firstImage.size.height)/2))]; 
    [secondImage drawAtPoint:CGPointMake(roundf((newImageSize.width-secondImage.size.width)/2), 
                                         roundf((newImageSize.height-secondImage.size.height)/2))]; 
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}