UIView+ScreenShot.m 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // UIView+ScreenShot.m
  3. // shiku_im
  4. //
  5. // Created by Apple on 16/12/7.
  6. // Copyright © 2016年 Reese. All rights reserved.
  7. //
  8. #import "UIView+ScreenShot.h"
  9. @implementation UIView (ScreenShot)
  10. - (UIImage *)screenshot
  11. {
  12. return [self screenshotWithRect:self.bounds];
  13. }
  14. - (UIImage *)screenshotWithRect:(CGRect)rect;
  15. {
  16. UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
  17. CGContextRef context = UIGraphicsGetCurrentContext();
  18. if (context == NULL)
  19. {
  20. return nil;
  21. }
  22. CGContextSaveGState(context);
  23. CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
  24. //[self layoutIfNeeded];
  25. if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
  26. {
  27. [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
  28. }
  29. else
  30. {
  31. [self.layer renderInContext:context];
  32. }
  33. CGContextRestoreGState(context);
  34. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  35. UIGraphicsEndImageContext();
  36. // NSData *imageData = UIImageJPEGRepresentation(image, 1); // convert to jpeg
  37. // image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];
  38. return image;
  39. }
  40. - (UIImage *)snapshot:(UIView *)view
  41. {
  42. UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
  43. [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
  44. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  45. UIGraphicsEndImageContext();
  46. return image;
  47. }
  48. - (UIImage *)viewSnapshot:(UIView *)view withInRect:(CGRect)rect
  49. {
  50. // UIGraphicsBeginImageContext(view.bounds.size);
  51. UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO,[UIScreen mainScreen].scale);
  52. [view.layer renderInContext:UIGraphicsGetCurrentContext()];
  53. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  54. UIGraphicsEndImageContext();
  55. // image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage,rect)];
  56. return image;
  57. }
  58. + (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
  59. {
  60. // UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
  61. UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize), NO,[UIScreen mainScreen].scale);
  62. [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
  63. UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  64. UIGraphicsEndImageContext();
  65. return scaledImage;
  66. }
  67. @end