调整大小uiimage在调整大小后不给我确切的新大小

时间:2015-03-02 12:03:22

标签: ios xcode resize uiimage

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));    //CGSize is 51*51
CGImageRef imageRef = image.CGImage;

UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();

// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);

CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);

// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
 NSLog(@"size of resizeimage is %@",NSStringFromCGSize(newImage.size));    // here i get 102*102
return newImage;
}

我输入的是51 * 51的cgsize,

并且在调整大小后我检查尺寸时给我102 * 102。

为什么?请解决我的问题。

2 个答案:

答案 0 :(得分:1)

查看您的UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);,从Apple文档中,scale参数表示:

The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

因此,如果它是视网膜显示器,那是正常的。

答案 1 :(得分:0)

我已按照此方法调整图像大小

-(UIImage *)resizeImage:(UIImage *)image newSize:(CGSize)newSize
{
    float actualHeight = image.size.height;
    float actualWidth = image.size.width;
    float maxHeight = newSize.height;  
    float maxWidth = newSize.width;  
    float imgRatio = actualWidth/actualHeight;
    float maxRatio = maxWidth/maxHeight;

    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();
   UIGraphicsEndImageContext();


   NSLog(@"size of resizeimage is %@",NSStringFromCGSize(img.size));
   NSLog(@"size of original is %@",NSStringFromCGSize(image.size));


   return img;

  }