[程序員日記]iOS截圖(1)生成分享圖片

在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的截圖的拓展:

iOS截圖(2)生成長圖
iOS截圖(3)截取網(wǎng)頁片段

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容