renderInContext:生成带有模糊文本的图像

时间:2012-04-15 22:44:42

标签: ios cocoa-touch uikit

我正在使用几个不同的UIImageViews和UILabels预渲染合成图像,以加快大型桌面视图中的滚动。不幸的是,与同一视图中的其他UILabel相比,主UILabel看起来有点模糊。

黑色字母“PLoS ONE”位于UILabel中,它们看起来比“医疗”或“医学”更加模糊。标识“PLoS one”可能同样模糊不清,但它并不像清晰的文字那么明显 整个杂志封面是分配给UIButton的单个UIImage。

PLoS ONE label is blurry than "Medical Special" and "Medicine (Gener)" http://karlbecker.com/screen_blurry.png

这是我用来绘制图像的代码。 magazineView是一个125 x 151像素的矩形。 我尝试过不同的缩放品质,但这并没有改变任何东西。它不应该,因为缩放不应该完全不同。我正在分配此图像的UIButton与magazineView完全相同。

    UIGraphicsBeginImageContextWithOptions(magazineView.bounds.size, NO, 0.0);
    [magazineView.layer renderInContext:UIGraphicsGetCurrentContext()];
    [coverImage release];
    coverImage = UIGraphicsGetImageFromCurrentImageContext();
    [coverImage retain];
    UIGraphicsEndImageContext();

为什么它模糊不清?

当我开始使用图像上下文并立即渲染时,渲染是在偶数像素上进行的,还是我需要手动设置渲染的位置?

3 个答案:

答案 0 :(得分:6)

确保标签坐标是整数值。如果它们不是整数,它们将显得模糊。

答案 1 :(得分:1)

我认为您需要使用CGRectIntegral获取更多信息,请参阅: What is the usage of CGRectIntegral? Reference of CGRectIntegral

答案 2 :(得分:0)


我今天遇到了同样的问题,当我从UILabel文本生成图像时,我的内容被像素化了。

我们使用UIGraphicsBeginImageContextWithOptions()来配置绘图环境以渲染成接受三个参数的位图:

size:新位图上下文的大小。这表示由UIGraphicsGetImageFromCurrentImageContext函数返回的图像的大小。

opaque:一个布尔型标志,指示位图是否不透明。如果opaque参数为YES,则将忽略Alpha通道,并将位图视为完全不透明。

scale:应用于位图的比例因子。如果您将值指定为0.0,则比例因子将设置为设备主屏幕的比例因子。

因此,我们应该针对设备显示屏使用适当的比例因子(1x,2x,3x)来解决此问题。

Swift 5版本:

UIGraphicsBeginImageContextWithOptions(frame.size, true, UIScreen.main.scale)
if let currentContext = UIGraphicsGetCurrentContext() {
    nameLabel.layer.render(in: currentContext)
    let nameImage = UIGraphicsGetImageFromCurrentImageContext()
    return nameImage
}