我正在使用以下代码对我加载的图像执行一些操作,但我发现当它在视网膜显示器上时显示变得模糊
- (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
答案 0 :(得分:48)
CGImages没有考虑您设备的Retina-ness,所以您必须自己这样做。
要做到这一点,您需要将所有在CoreGraphics例程中使用的坐标和大小乘以输入图像的scale
属性(在Retina设备上为2.0),以确保您在双重决议。
然后,您需要将resultImage
的初始化更改为使用initWithCGImage:scale:orientation:
并输入相同的比例因子。这就是Retina设备以原始分辨率渲染输出而不是像素加倍分辨率的原因。
答案 1 :(得分: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;
}
答案 2 :(得分:2)
Swift版本:
let scale = UIScreen.mainScreen().scale
CGContextScaleCTM(UIGraphicsGetCurrentContext(), scale, scale)