在iOS開發(fā)中,經(jīng)常會遇到分享到微博微信時需要附帶一張分享圖片,圖片中需要分享的相關(guān)信息(如產(chǎn)品二維碼,分享人信息等)。
(1)首先要創(chuàng)建一個View重寫initWithFrame方法將要分享的內(nèi)容布局到上面
(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;
}
后期調(diào)整
設(shè)置水印大小,為了防止微博分享時生成的水印會擋住二維碼,因此將分享的圖片延長。
CGFloat heightWithShuiYin = 40.0;//設(shè)置圖片延長的長度
更改圖片的大小
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)];
分享結(jié)果如圖:

微博分享截圖
有關(guān)iOS的截圖的拓展: