iOS UIImage维度更改无法正常工作

时间:2016-06-18 10:55:17

标签: ios objective-c uiimageview compression

我正在通过更改维度来调整UIImage的大小。但它显示出不同的维度。对于iPhone 6,我选择1.25时间而不是屏幕尺寸937 * 1667。但完成我的调整大小操作后变为938 * 1251。我需要它在声明的维度。

我的代码是:

    NSData *imageData;
    imageData=[[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)];

    CGSize sz;
    sz.width=((isIphone4||isIphone5)?320*2.3:iPhone6?750*1.25:414*1.8);
    sz.height=((isIphone4||isIphone5)?568*2.3:iPhone6?667*1.25:768*1.8);

    if([imageData length]/1024>400)
        image=[self resizeImage:image scaledToSize:sz];

 //function call

-(UIImage *)resizeImage:(UIImage *)image scaledToSize:(CGSize)targetSize
{
   float actualHeight = image.size.height;
   float actualWidth = image.size.width;
   float maxHeight = targetSize.height;
   float maxWidth = targetSize.width;
   float imgRatio = actualWidth/actualHeight;
   float maxRatio = maxWidth/maxHeight;
   float compressionQuality = 0.50;//50 percent compression

   if (actualHeight > maxHeight || actualWidth > maxWidth)
   {
      if(imgRatio < maxRatio)
      {
        //adjust width according to maxHeight
        imgRatio = maxHeight / actualHeight;
        actualWidth = imgRatio * actualWidth;
        actualHeight = maxHeight;
    }
    else if(imgRatio > maxRatio)
    {
        //adjust height according to maxWidth
        imgRatio = maxWidth / actualWidth;
        actualHeight = imgRatio * actualHeight;
        actualWidth = maxWidth;
    }
    else
    {
        actualHeight = maxHeight;
        actualWidth = maxWidth;
    }
}

CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];

}

什么可以解决正确的尺寸?

1 个答案:

答案 0 :(得分:0)

是的,最后我在几个小时后解决了。我试错了。实际上,当我们在特定的内存大小中调整大小时,维度无法修复。以下方法将图像转换为范围大小(字节),维度将由方法本身定义。

     NSData *imageData;
    imageData=[[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)];
    CGFloat scale= (400*1024)/(CGFloat)[imageData length];
    UIImage *small_image=[UIImage imageWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
    imageData = UIImageJPEGRepresentation(small_image, scale);