Guest User

imageByScalingProportionallyToSize

a guest
Aug 13th, 2012
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. -(UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize ImageForConvert:(UIImage *)sourceImage
  3. {
  4.     UIImage *newImage = nil;
  5.    
  6.     CGSize imageSize = sourceImage.size;
  7.     CGFloat width = imageSize.width;
  8.     CGFloat height = imageSize.height;
  9.    
  10.     CGFloat targetWidth = targetSize.width;
  11.     CGFloat targetHeight = targetSize.height;
  12.    
  13.     CGFloat scaleFactor = 0.0;
  14.     CGFloat scaledWidth = targetWidth;
  15.     CGFloat scaledHeight = targetHeight;
  16.    
  17.     CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
  18.    
  19.     if (CGSizeEqualToSize(imageSize, targetSize) == NO)
  20.     {
  21.        
  22.         CGFloat widthFactor = targetWidth / width;
  23.         CGFloat heightFactor = targetHeight / height;
  24.        
  25.         if (widthFactor < heightFactor)
  26.             scaleFactor = widthFactor;
  27.         else
  28.             scaleFactor = heightFactor;
  29.        
  30.         scaledWidth  = width * scaleFactor*1;
  31.         scaledHeight = height * scaleFactor;
  32.        
  33.         // center the image
  34.        
  35.         if (widthFactor < heightFactor)
  36.         {
  37.             thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
  38.         } else if (widthFactor > heightFactor) {
  39.             thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
  40.         }
  41.     }
  42.    
  43.    
  44.     UIGraphicsBeginImageContext(targetSize);
  45.    
  46.     CGRect thumbnailRect = CGRectZero;
  47.     thumbnailRect.origin = thumbnailPoint;
  48.     thumbnailRect.size.width  = scaledWidth;
  49.     thumbnailRect.size.height = scaledHeight;
  50.    
  51.     [sourceImage drawInRect:thumbnailRect];
  52.    
  53.     newImage = UIGraphicsGetImageFromCurrentImageContext();
  54.     UIGraphicsEndImageContext();
  55.     return newImage ;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment