UIImage调整大小并裁剪以适应框架

时间:2013-07-18 14:14:07

标签: objective-c uiimage

我知道这个问题已被问过几次,但他们的回答使我的图像质量松散。它们都变得像素化了。因此,即使它正确地裁剪和调整大小,它也会失去质量。

这样你可以检查它,这是每个帖子中的算法:

- (UIImage*)scaleAndCropImage:(UIImage *)aImage forSize:(CGSize)targetSize
{
UIImage *sourceImage = aImage;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (CGSizeEqualToSize(imageSize, targetSize) == NO)
{
    CGFloat widthFactor = targetWidth / width;
    CGFloat heightFactor = targetHeight / height;

    if (widthFactor > heightFactor)
    {
        scaleFactor = widthFactor; // scale to fit height
    }
    else
    {
        scaleFactor = heightFactor; // scale to fit width
    }

    scaledWidth  = width * scaleFactor;
    scaledHeight = height * scaleFactor;

    // center the image
    if (widthFactor > heightFactor)
    {
        thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
    }
    else
    {
        if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
}

UIGraphicsBeginImageContext(targetSize); // this will crop

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();

if(newImage == nil)
{
    NSLog(@"could not scale image");
}

//pop the context to get back to the default
UIGraphicsEndImageContext();

return newImage;
 }

2 个答案:

答案 0 :(得分:5)

在您开始使用UIGraphicsImageContext的行上,使用UIGraphicsBeginImageContextWithOptions代替UIGraphicsBeginImageContext。尝试这样的事情:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0)

注意上面传递的三个参数,我将按顺序查看它们:

  1. targetSize是以点(不是像素)
  2. 测量的图像大小
  3. NO是BOOL值(可以是YES或NO),表示图像是否100%不透明。将此设置为NO将保留透明度并创建Alpha通道以处理透明度。
  4. 上述代码的最重要部分是最终参数0.0。这是将应用的图像比例因子。将值指定为0.0可设置当前设备屏幕的比例因子。这意味着质量将得到保留,并且在Retina Displays上看起来特别好。
  5. 以下是UIGraphicsBeginImageContextWithOptions上的Apple Documentation

答案 1 :(得分:0)

您应该使用UIGraphicsBeginImageContextWithOptions(targetSize, false, 0.0)代替UIGraphicsBeginImageContext(targetSize),以便将正确的比例因子应用于位图。

将0.0指定为比例因子,将比例因子设置为设备主屏幕的比例因子。 仅呼叫UIGraphicsBeginImageContext()与呼叫相同 UIGraphicsBeginImageContextWithOptions(..),比例因子为1.0

有关详细信息,请查看:http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/c/func/UIGraphicsBeginImageContextWithOptions