用于视网膜显示的CoreGraphics

DKV*_*DKV 30 iphone cg core-graphics retina-display

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

- (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;
}
Run Code Online (Sandbox Code Playgroud)

如何更改此设置以使其与视网膜兼容.

在此先感谢您的帮助

最好的,DV

gra*_*rks 48

CGImages没有考虑您设备的Retina-ness,所以您必须自己这样做.

要做到这一点,你需要将输入图像的scale属性(在Retina设备上为2.0)乘以CoreGraphics例程中使用的所有坐标和大小,以确保以双倍分辨率完成所有操作.

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

  • 对不起,评论太快了,编辑太迟了.如果你这样做,你不需要考虑自己缩放所有坐标:`CGFloat scale = [[UIScreen mainScreen] scale]; CGContextScaleCTM(UIGraphicsGetCurrentContext(),scale,scale);` (14认同)

Gen*_*ode 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;
}
Run Code Online (Sandbox Code Playgroud)