UIImage的drawInrect:平滑图像

ton*_*ony 16 antialiasing uikit uiimage ios

我想用绘制图像UIImagedrawInRect:方法.这是代码:

UIImage *image = [UIImage imageNamed:@"OrangeBadge.png"];

UIGraphicsBeginImageContext(image.size);

[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];

UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

问题是生成的图像模糊.这是与源图像(左侧)相比得到的图像(在右侧):

源图像和模糊的图像

我试过了两个,CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), NO) CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), NO)但这并没有解决问题.

有任何想法吗?

提前致谢.

ser*_*gio 30

如果您正在使用视网膜设备进行开发,则问题可能与图形上下文的分辨率有关.你会尝试:

UIGraphicsBeginImageContextWithOptions(size, NO, 2.0f);
Run Code Online (Sandbox Code Playgroud)

这将使视网膜分辨率.此外,您的图像应以@ 2x分辨率提供,以便工作.

如果您也想支持非视网膜设备,您可以使用:

if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0f);
} else {
    UIGraphicsBeginImageContext(newSize);
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用`[UIScreen mainScreen] .scale`而不是硬编码`@ 2x`,因为iPhone 6 +的刻度是3倍. (3认同)
  • 我不建议使用`==`来检查浮点相等性.您所要做的就是将比例设置为"0.f",框架将负责其余部分.(参见http://stackoverflow.com/questions/2765537/how-do-i-use-the-nsstring-draw-functionality-to-create-a-uiimage-from-text) (2认同)