你好,歡迎來到IOS教程網

 Ios教程網 >> IOS訊息 >> 關於IOS >> 圖像壓縮成指定大小(高度/寬度)

圖像壓縮成指定大小(高度/寬度)

編輯:關於IOS

圖像壓縮成指定大小(高度/寬度)

  1. #import <Foundation/Foundation.h>
  2. @interface UIImage (UIImageExt)
  3. - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;
  4. @end

 

復制代碼

  1. #import "UIImageExt.h"
  2. @implementation UIImage (UIImageExt)
  3. - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
  4. {
  5.     UIImage *sourceImage = self;
  6.     UIImage *newImage = nil;
  7.     CGSize imageSize = sourceImage.size;
  8.     CGFloat width = imageSize.width;
  9.     CGFloat height = imageSize.height;
  10.     CGFloat targetWidth = targetSize.width;
  11.     CGFloat targetHeight = targetSize.height;
  12.     CGFloat scaleFactor = 0.0;
  13.     CGFloat scaledWidth = targetWidth;
  14.     CGFloat scaledHeight = targetHeight;
  15.     CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
  16.     if (CGSizeEqualToSize(imageSize, targetSize) == NO)
  17.     {
  18.         CGFloat widthFactor = targetWidth / width;
  19.         CGFloat heightFactor = targetHeight / height;
  20.         if (widthFactor > heightFactor)
  21.             scaleFactor = widthFactor; // scale to fit height
  22.         else
  23.             scaleFactor = heightFactor; // scale to fit width
  24.         scaledWidth  = width * scaleFactor;
  25.         scaledHeight = height * scaleFactor;
  26.         // center the image
  27.         if (widthFactor > heightFactor)
  28.         {
  29.             thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
  30.         }
  31.         else
  32.             if (widthFactor < heightFactor)
  33.             {
  34.                 thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
  35.             }
  36.     }
  37.     UIGraphicsBeginImageContext(targetSize); // this will crop
  38.     CGRect thumbnailRect = CGRectZero;
  39.     thumbnailRect.origin = thumbnailPoint;
  40.     thumbnailRect.size.width  = scaledWidth;
  41.     thumbnailRect.size.height = scaledHeight;
  42.     [sourceImage drawInRect:thumbnailRect];
  43.     newImage = UIGraphicsGetImageFromCurrentImageContext();
  44.     if(newImage == nil)
  45.         NSLog(@"could not scale image");
  46.     //pop the context to get back to the default
  47.     UIGraphicsEndImageContext();
  48.     return newImage;
  49. }
  50. @end
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved