在iOS開發(fā)中旧烧,經常會遇到分享到微博微信時需要附帶一張分享圖片研儒,圖片中需要分享的相關信息(如產品二維碼,分享人信息等)贬芥。
(1)首先要創(chuàng)建一個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)];
分享結果如圖:
有關iOS的截圖的拓展: