UIImage+CropRotate.m 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // UIImage+CropRotate.m
  3. //
  4. // Copyright 2015 Timothy Oliver. All rights reserved.
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to
  8. // deal in the Software without restriction, including without limitation the
  9. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  10. // sell copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  20. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
  21. // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. #import "UIImage+CropRotate.h"
  23. @implementation UIImage (CropRotate)
  24. - (UIImage *)croppedImageWithFrame:(CGRect)frame angle:(NSInteger)angle
  25. {
  26. UIImage *croppedImage = nil;
  27. CGPoint drawPoint = CGPointZero;
  28. UIGraphicsBeginImageContextWithOptions(frame.size, YES, self.scale);
  29. {
  30. CGContextRef context = UIGraphicsGetCurrentContext();
  31. //To conserve memory in not needing to completely re-render the image re-rotated,
  32. //map the image to a view and then use Core Animation to manipulate its rotation
  33. if (angle != 0) {
  34. UIImageView *imageView = [[UIImageView alloc] initWithImage:self];
  35. imageView.layer.minificationFilter = @"nearest";
  36. imageView.layer.magnificationFilter = @"neareset";
  37. imageView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, angle * (M_PI/180.0f));
  38. CGRect rotatedRect = CGRectApplyAffineTransform(imageView.bounds, imageView.transform);
  39. UIView *containerView = [[UIView alloc] initWithFrame:(CGRect){CGPointZero, rotatedRect.size}];
  40. [containerView addSubview:imageView];
  41. imageView.center = containerView.center;
  42. CGContextTranslateCTM(context, -frame.origin.x, -frame.origin.y);
  43. [containerView.layer renderInContext:context];
  44. }
  45. else {
  46. CGContextTranslateCTM(context, -frame.origin.x, -frame.origin.y);
  47. [self drawAtPoint:drawPoint];
  48. }
  49. croppedImage = UIGraphicsGetImageFromCurrentImageContext();
  50. }
  51. UIGraphicsEndImageContext();
  52. return croppedImage;
  53. }
  54. @end