3

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

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

- (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;
 }
4

2 回答 2

5

在您开始 UIGraphicsImageContext 的那一行,使用UIGraphicsBeginImageContextWithOptions而不是UIGraphicsBeginImageContext. 尝试这样的事情:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0)

注意上面传递的三个参数,我将依次遍历它们:

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

这是关于UIGraphicsBeginImageContextWithOptions.

于 2013-07-18T14:58:59.140 回答
0

您应该使用UIGraphicsBeginImageContextWithOptions(targetSize, false, 0.0)而不是UIGraphicsBeginImageContext(targetSize)将正确的比例因子应用于位图。

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

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

于 2013-07-19T07:37:23.683 回答