iOS截图(1)生成分享图片

在iOS开发中,经常会遇到分享到微博微信时需要附带一张分享图片,图片中需要分享的相关信息(如产品二维码,分享人信息等)。

(1)首先要创建一个View重写initWithFrame方法将要分享的内容布局到上面

(2)新建方法 - (UIImage *)snapshotViewFromRect:(CGRect)rect withCapInsets:(UIEdgeInsets)capInsets 生成图片

- (UIImage *)snapshotViewFromRect:(CGRect)rect withCapInsets:(UIEdgeInsets)capInsets {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(currentContext, - CGRectGetMinX(rect), - CGRectGetMinY(rect));
    [self.layer renderInContext:currentContext];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImageView *snapshotView = [[UIImageView alloc] initWithFrame:rect];

    snapshotView.image = [snapshotImage resizableImageWithCapInsets:capInsets];
    return snapshotView.image;
}

后期调整
设置水印大小,为了防止微博分享时生成的水印会挡住二维码,因此将分享的图片延长。

CGFloat heightWithShuiYin = 40.0;//设置图片延长的长度

更改图片的大小
UIGraphicsBeginImageContextWithOptions(CGSizeMake(rect.size.width, rect.size.height + heightWithShuiYin), NO, [UIScreen mainScreen].scale);

UIImageView * snapshotView = [[UIImageView alloc]initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height + heightWithShuiYin)];

分享结果如图:

微博分享截图