春水初生,春林初盛煞躬,春風(fēng)十里肛鹏,不如你。
前言
在開發(fā)過程中恩沛,不免遇到屏幕截圖分享在扰,截圖添加水印等。本文就記錄一下自己項(xiàng)目中分享截圖時寫的代碼雷客,小白們可以參考一下芒珠,大神們請繞行。
- 屏幕截圖
UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT), NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:ctx];
// 這個就是截圖
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
- 添加水印
// 畫水印 rect:水印圖片相對于截圖的位置
- (UIImage *)originImage:(UIImage *)originImage withWaterMask:(UIImage *)mask inRect:(CGRect)rect {
UIGraphicsBeginImageContextWithOptions(originImage.size, NO, 0); // 0.0 for scale means "scale for device's main screen".
//原圖
[originImage drawInRect:CGRectMake(0, 0, originImage.size.width, originImage.size.height)];
//水印圖
[mask drawInRect:rect];
UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newPic;
}
- 截取scrollView或者tableView長圖
UIImage* viewImage = nil;
UITableView *scrollView = self.tableView;
//我把contentSize.height加了一個值搅裙,是因?yàn)槲乙陂L圖底部添加圖片
UIGraphicsBeginImageContextWithOptions(CGSizeMake(scrollView.contentSize.width, scrollView.contentSize.height + kRelativeHeight(121)), scrollView.opaque, 0.0);
//記錄用戶點(diǎn)擊分享時視圖的偏移量皱卓、位置
CGPoint savedContentOffset = scrollView.contentOffset;
CGRect savedFrame = scrollView.frame;
//把偏移量置為,從頂部開始截圖
scrollView.contentOffset = CGPointZero;
scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
[scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
//恢復(fù)到用戶點(diǎn)擊時的狀態(tài)
scrollView.contentOffset = savedContentOffset;
scrollView.frame = savedFrame;
UIGraphicsEndImageContext();