iOS2012. 9. 10. 21:57

iOS 개발 하다 보니 image를 crop 하거나 resize를 해야 하는 경우가 많더구요.

구글링 해보니 괜찮게 만들어 놓은 소스도 많아서 참고해서 UIImage에 Category로 만들어서 사용하고 있습니다. 


  1. @implementation UIImage ( NBUIImageCrop )
  2. - (UIImage *)crop:(CGRect)rect {
  3.     if (self.scale > 1.0f) {
  4.         rect = CGRectMake(rect.origin.* self.scale,
  5.                           rect.origin.* self.scale,
  6.                           rect.size.width * self.scale,
  7.                           rect.size.height * self.scale);
  8.     }
  9.    
  10.     if ([self imageOrientation] == UIImageOrientationLeft) {
  11.         rect.size = CGSizeMake(rect.size.height, rect.size.width);
  12.         rect.size = CGSizeMake(rect.size.height, rect.size.width);
  13.         rect.origin = CGPointMake(rect.origin.y, rect.origin.x);
  14.     }
  15.     else if ([self imageOrientation] == UIImageOrientationRight) {
  16.         rect.size = CGSizeMake(rect.size.height, rect.size.width);
  17.         rect.origin = CGPointMake(rect.origin.y, rect.origin.x);
  18.     }
  19.  
  20.     CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
  21.     UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
  22.     CGImageRelease(imageRef);
  23.     return result;
  24. }
  25.  
  26. - (UIImage *)resizeToFitWidth:(CGFloat)width
  27. {
  28.     CGSize size = CGSizeMake(width, self.size.height * width/self.size.width);
  29.     UIGraphicsBeginImageContext(size);
  30.     [self drawInRect:CGRectMake(0,0,size.width,size.height)];
  31.     UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  32.     UIGraphicsEndImageContext();
  33.     return newImage;
  34. }

Posted by 다오나무