UIView+Screenshot.m 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // UIView+Screenshot.m
  3. // WildFireChat
  4. //
  5. // Created by heavyrain lee on 02/01/2018.
  6. // Copyright © 2018 WildFireChat. 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. if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
  25. {
  26. [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
  27. }
  28. else
  29. {
  30. [self.layer renderInContext:context];
  31. }
  32. CGContextRestoreGState(context);
  33. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  34. UIGraphicsEndImageContext();
  35. return image;
  36. }
  37. @end