30

我正在使用以下代码对我加载的图像执行一些操作,但我发现当它在视网膜显示器上时显示变得模糊

- (UIImage*)createImageSection:(UIImage*)image section:(CGRect)section

{
float originalWidth = image.size.width ;
float originalHeight = image.size.height ;
int w = originalWidth * section.size.width;
int h = originalHeight * section.size.height;

CGContextRef ctx = CGBitmapContextCreate(nil, w, h, 8, w * 8,CGImageGetColorSpace([image CGImage]), kCGImageAlphaPremultipliedLast);
CGContextClearRect(ctx, CGRectMake(0, 0, originalWidth * section.size.width, originalHeight * section.size.height)); // w + h before
CGContextTranslateCTM(ctx, (float)-originalWidth * section.origin.x, (float)-originalHeight * section.origin.y);
CGContextDrawImage(ctx, CGRectMake(0, 0, originalWidth, originalHeight), [image CGImage]);
CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
UIImage* resultImage = [[UIImage alloc] initWithCGImage:cgImage];

CGContextRelease(ctx);
CGImageRelease(cgImage);

return resultImage;
}

我如何更改它以使其与视网膜兼容。

在此先感谢您的帮助

最佳,DV

4

3 回答 3

48

CGImages 不考虑您设备的 Retina-ness,因此您必须自己这样做。

为此,您需要将 CoreGraphics 例程中使用的所有坐标和大小乘以输入图像的scale属性(在 Retina 设备上为 2.0),以确保以双倍分辨率进行所有操作。

然后您需要更改初始化resultImage以使用initWithCGImage:scale:orientation:并输入相同的比例因子。这就是使 Retina 设备以原始分辨率而不是像素加倍分辨率呈现输出的原因。

于 2011-01-16T19:43:27.047 回答
5

感谢您的回答,帮助了我!无论如何要更清楚,OP的代码应该像这样更改:

- (UIImage*)createImageSection:(UIImage*)image section:(CGRect)section        
{
    CGFloat scale = [[UIScreen mainScreen] scale]; ////// ADD

    float originalWidth = image.size.width ;
    float originalHeight = image.size.height ;
    int w = originalWidth * section.size.width *scale; ////// CHANGE
    int h = originalHeight * section.size.height *scale; ////// CHANGE

    CGContextRef ctx = CGBitmapContextCreate(nil, w, h, 8, w * 8,CGImageGetColorSpace([image CGImage]), kCGImageAlphaPremultipliedLast);
    CGContextClearRect(ctx, CGRectMake(0, 0, originalWidth * section.size.width, originalHeight * section.size.height)); // w + h before
    CGContextTranslateCTM(ctx, (float)-originalWidth * section.origin.x, (float)-originalHeight * section.origin.y);

    CGContextScaleCTM(UIGraphicsGetCurrentContext(), scale, scale); ////// ADD

    CGContextDrawImage(ctx, CGRectMake(0, 0, originalWidth, originalHeight), [image CGImage]);
    CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
    UIImage* resultImage = [[UIImage alloc] initWithCGImage:cgImage];

    CGContextRelease(ctx);
    CGImageRelease(cgImage);

    return resultImage;
}
于 2012-11-21T06:36:04.627 回答
2

斯威夫特版本:

    let scale = UIScreen.mainScreen().scale

    CGContextScaleCTM(UIGraphicsGetCurrentContext(), scale, scale)
于 2016-01-06T09:26:08.700 回答