UIImage+ImageRotate.m 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // UIImage+ImageRotate.m
  3. // LenzSDK
  4. //
  5. // Created by lr on 2023/5/18.
  6. //
  7. #import "UIImage+ImageRotate.h"
  8. #import <QuartzCore/QuartzCore.h>
  9. #import <Accelerate/Accelerate.h>
  10. @implementation UIImage (ImageRotate)
  11. #pragma mark - 图片旋转
  12. // 1 image --> Context 2. context 3. context --> image
  13. - (UIImage *)imageRotateWithIndegree:(CGFloat)indegree {
  14. // 1. image --> context
  15. size_t width = (size_t)(self.size.height * self.scale);
  16. size_t height = (size_t)(self.size.width * self.scale);
  17. size_t bytesPerRow = width * 4; // 每行图片字节数
  18. CGImageAlphaInfo alphaInfo = kCGImageAlphaPremultipliedFirst; // alpha
  19. CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGBitmapByteOrderDefault | alphaInfo);
  20. if (!bmContext) {
  21. return nil;
  22. }
  23. CGContextDrawImage(bmContext, CGRectMake(0, 0, width, height), self.CGImage);
  24. // 2. 旋转
  25. UInt8 * data = (UInt8 *)CGBitmapContextGetData(bmContext);
  26. // 需要引入 #import <Accelerate/Accelerate.h> 解释这个类干什么用的
  27. vImage_Buffer src = {data,height,width,bytesPerRow};
  28. vImage_Buffer dest = {data,height,width,bytesPerRow};
  29. Pixel_8888 bgColor = {0,0,0,0};
  30. vImageRotate_ARGB8888(&src, &dest, NULL, indegree, bgColor, kvImageBackgroundColorFill);
  31. // 3. context --> UIImage
  32. CGImageRef rotateImageRef = CGBitmapContextCreateImage(bmContext);
  33. UIImage * rotateImage = [UIImage imageWithCGImage:rotateImageRef scale:self.scale orientation:self.imageOrientation];
  34. CGContextRelease(bmContext);
  35. CGImageRelease(rotateImageRef);
  36. return rotateImage;
  37. }
  38. @end