無論是從用戶體驗角度還是產品運營角度截圖分享功能已經覆蓋大部分的APP。本文不介紹如何分享,只介紹幾種截屏的方法(原理相同)!希望能幫助有需要的朋友。
不同的產品對功能的需求有所不同,有些APP只要求截取一屏的內容,有些APP需要截取超出一屏的內容。
方法1.截取UIScrollView上所有內容
- (UIImage *)captureScrollView:(UIScrollView *)scrollView {
UIImage *image = nil;
//第一個參數表示區域大小。第二個參數表示是否是非透明的。如果需要顯示半透明效果,需要傳NO,否則傳YES。第三個參數就是屏幕密度了,設置為[UIScreen mainScreen].scale可以保證轉成的圖片不失真。
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的內容
- (UIImage *)createImageWithView:(UIView *)view
{
CGSize s = view.bounds.size;
//第一個參數表示區域大小。第二個參數表示是否是非透明的。如果需要顯示半透明效果,需要傳NO,否則傳YES。第三個參數就是屏幕密度了,設置為[UIScreen mainScreen].scale可以保證轉成的圖片不失真。
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.對圖片進行壓縮和裁剪
- (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指定區域的圖片
- ( UIImage *)getImageByCuttingImage:( UIImage *)image ToRect:( CGRect )rect{
// 大圖 bigImage
// 定義 myImageRect ,截圖的區域
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;
}