Posted By

oppey on 05/23/11


Tagged


Versions (?)

アスペクト比(縦横比)を保ったまま、画像を拡大縮小する。


 / Published in: Objective C
 

  1. @interface UIImage (Extras)
  2. - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
  3. @end;
  4.  
  5.  
  6.  
  7.  
  8.  
  9. @implementation UIImage (Extras)
  10.  
  11. - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
  12. UIImage *sourceImage = self;
  13. UIImage *newImage = nil;
  14.  
  15. CGSize imageSize = sourceImage.size;
  16. CGFloat width = imageSize.width;
  17. CGFloat height = imageSize.height;
  18.  
  19. CGFloat targetWidth = targetSize.width;
  20. CGFloat targetHeight = targetSize.height;
  21.  
  22. CGFloat scaleFactor = 0.0f;
  23. CGFloat scaledWidth = targetWidth;
  24. CGFloat scaledHeight = targetHeight;
  25.  
  26. CGPoint thumbnailPoint = CGPointMake(0.0f, 0.0f);
  27.  
  28. if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
  29. CGFloat widthFactor = targetWidth / width;
  30. CGFloat heightFactor = targetHeight / height;
  31.  
  32. if (widthFactor < heightFactor) {
  33. scaleFactor = widthFactor;
  34. } else {
  35. scaleFactor = heightFactor;
  36. }
  37.  
  38. scaledWidth = width * scaleFactor;
  39. scaledHeight = height * scaleFactor;
  40.  
  41. // center the image
  42. if (widthFactor < heightFactor) {
  43. thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5f;
  44. } else if (widthFactor > heightFactor) {
  45. thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5f;
  46. }
  47. }
  48.  
  49. // this is actually the interesting part:
  50. UIGraphicsBeginImageContext(targetSize);
  51.  
  52. [[UIColor blackColor] set];
  53. CGContextRef context = UIGraphicsGetCurrentContext();
  54. CGContextFillRect(context, CGRectMake(0.0f, 0.0f, targetWidth, targetHeight));
  55.  
  56. CGRect thumbnailRect = CGRectZero;
  57. thumbnailRect.origin = thumbnailPoint;
  58. thumbnailRect.size.width = scaledWidth;
  59. thumbnailRect.size.height = scaledHeight;
  60.  
  61. [sourceImage drawInRect:thumbnailRect];
  62.  
  63. newImage = UIGraphicsGetImageFromCurrentImageContext();
  64. UIGraphicsEndImageContext();
  65.  
  66. if (newImage == nil) NSLog(@"could not scale image");
  67.  
  68. return newImage ;
  69. }
  70.  
  71. @end
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81. //---------using
  82.  
  83.  
  84.  
  85. UIImage *newImage = nil;
  86.  
  87. CGSize targetSize;
  88. targetSize.width = 70;
  89. targetSize.height = 70;
  90. newImage = [imageData imageByScalingProportionallyToSize: targetSize];
  91.  
  92.  
  93.  
  94.  
  95.  

Report this snippet  

You need to login to post a comment.