iOS设置图片最大尺寸不压缩

遇到类似上传头像、社交分享等操作的时候,需要对图片进行裁切,
一般需要限制一个最大值,来限制图片既要维持宽高比例,又要让宽高都小于这个最大值
下面这个方法即可满足需求,当宽高都小于最大值的时候,不对图片进行压缩大小。当图片是竖排版(高>宽)的时候,把图片的高压缩到设置的最大值,同时宽按比例压缩到对应大小。同理,当图片是横版(高<宽),把宽设置成最大值,高按比例缩小。
压缩图片的原理,是利用Core Graphics来重绘图片
代码如下:

/* * *  压缩图片至目标尺寸 
* *     @param sourceImage 源图片 
*       @param maxValue 图片长宽最大值
* *     @return 返回按照源图片的宽、高比例压缩至目标宽、高的UIImage图片
*/
- (UIImage *)resizeImage:(UIImage *)sourceImage toMaxWidthAndHeight:(CGFloat)maxValue { 
   CGSize imageSize = sourceImage.size;   
   CGFloat width = imageSize.width;    
   CGFloat height = imageSize.height;    
  if (width > height && width > maxValue) {  
      height = height * (maxValue / width);    
      width = maxValue;    
   }else if (height > width && height > maxValue) {
        width = width * (maxValue / height);   
        height = maxValue;   
   }else {     
       return sourceImage;   
   }    
  UIGraphicsBeginImageContext(CGSizeMake(width, height));  
  [sourceImage drawInRect:CGRectMake(0, 0, width, height)];  
  UIImage *newImage = UIGraphicsGetImageFromCurrentImage
  Context();   
  UIGraphicsEndImageContext();   
  return newImage;
}

你可能感兴趣的:(iOS设置图片最大尺寸不压缩)