objective-c - UIImage 调整大小并裁剪以适合框架

标签 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;
 }

最佳答案

在开始 UIGraphicsImageContext 的行中,使用 UIGraphicsBeginImageContextWithOptions 而不是 UIGraphicsBeginImageContext。尝试这样的事情:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0)

请注意上面传递的三个参数,我将按顺序逐一介绍:

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

这是 Apple DocumentationUIGraphicsBeginImageContextWithOptions 上。

关于objective-c - UIImage 调整大小并裁剪以适合框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17725959/

相关文章:

c++ - 代码 : C++ error: unknown type name 'class' did you mean 'Class'

ios - 使用 UIImage - Swift 3.0 时如何刷新缓存以释放内存

ios - 在 Swift 中从属性检查器列表更改栏按钮图像

ios - Collection View 显示堆叠在单个 View 中的图像

ios - 将图像和标题都添加到分段控制 IOS

ios - 将包含 3 个字节 ASCII 字符的 NSString 编码为正确的 NSString

ios - 从另一个应用程序打开设置应用程序

objective-c - NSButton setEnabled 不起作用

objective-c - XCTAssertEqual 错误 : ("3") is not equal to ("3")

iphone - 如何从 UIWebView 获取整个图像,包括屏幕外内容