無(wú)論是從用戶體驗(yàn)角度還是產(chǎn)品運(yùn)營(yíng)角度截圖分享功能已經(jīng)覆蓋大部分的APP。本文不介紹如何分享,只介紹幾種截屏的方法(原理相同)!希望能幫助有需要的朋友。
不同的產(chǎn)品對(duì)功能的需求有所不同,有些APP只要求截取一屏的內(nèi)容,有些APP需要截取超出一屏的內(nèi)容。
方法1.截取UIScrollView上所有內(nèi)容
- (UIImage *)captureScrollView:(UIScrollView *)scrollView {
UIImage *image = nil;
//第一個(gè)參數(shù)表示區(qū)域大小。第二個(gè)參數(shù)表示是否是非透明的。如果需要顯示半透明效果,需要傳NO,否則傳YES。第三個(gè)參數(shù)就是屏幕密度了,設(shè)置為[UIScreen mainScreen].scale可以保證轉(zhuǎn)成的圖片不失真。
UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, NO, 0.0);
{
CGPoint savedContentOffset = scrollView.contentOffset;
CGRect savedFrame = scrollView.frame;
scrollView.frame = CGRectMake(0 , 0, scrollView.contentSize.width, scrollView.contentSize.height);
[scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
scrollView.contentOffset = savedContentOffset;
scrollView.frame = savedFrame;
}
UIGraphicsEndImageContext();
if (image != nil) {
return image;
}
return nil;
}
方法2.截取屏幕上指定view的內(nèi)容
- (UIImage *)createImageWithView:(UIView *)view
{
CGSize s = view.bounds.size;
//第一個(gè)參數(shù)表示區(qū)域大小。第二個(gè)參數(shù)表示是否是非透明的。如果需要顯示半透明效果,需要傳NO,否則傳YES。第三個(gè)參數(shù)就是屏幕密度了,設(shè)置為[UIScreen mainScreen].scale可以保證轉(zhuǎn)成的圖片不失真。
UIGraphicsBeginImageContextWithOptions(s, NO,[UIScreen mainScreen].scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
方法3.把兩張圖片合成為一張圖片
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {
UIGraphicsBeginImageContext(image1.size);
// Draw image1
[image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
// Draw image2
[image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}
方法4.對(duì)圖片進(jìn)行壓縮和裁剪
- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return UIImageJPEGRepresentation(newImage, 0.8);
}
方法5.截取image指定區(qū)域的圖片
- ( UIImage *)getImageByCuttingImage:( UIImage *)image ToRect:( CGRect )rect{
// 大圖 bigImage
// 定義 myImageRect ,截圖的區(qū)域
CGRect toImageRect = rect;
UIImage * bigImage= image;
CGImageRef imageRef = bigImage. CGImage ;
CGImageRef subImageRef = CGImageCreateWithImageInRect (imageRef, toImageRect);
CGSize size;
size. width = rect.size.width ;
size. height = rect.size.height ;
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext ();
CGContextDrawImage (context, toImageRect, subImageRef);
UIImage * smallImage = [ UIImage imageWithCGImage :subImageRef];
UIGraphicsEndImageContext();
return smallImage;
}