使用 renderInContext 添加 UILabel 到 UIImage

Adding a UILabel to UIImage with renderInContext

我已经尝试了很长时间来寻找将带有背景颜色的 UILabel 添加到 UIImage 的最佳方法。我需要将屏幕上显示的标签的精确副本添加到图像中,如果这对您有意义的话。

我发现最简单的方法是像这样使用 renderInContext:

    UIGraphicsBeginImageContext(self.view.bounds.size)
    self.view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let resultingImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    self.imageViewer.image = resultingImage
    UIGraphicsEndImageContext()

但这会使生成的图像像素化。我也知道你可以像这样在图片上写文字:

func addTextToImage(image:UIImage, text:NSString, pointof: CGPoint) -> UIImage{

    let font:UIFont = UIFont.boldSystemFontOfSize(14)
    let color: UIColor = UIColor.whiteColor()
    let attributeDict:NSDictionary = [NSFontAttributeName : font, NSForegroundColorAttributeName : color]

    UIGraphicsBeginImageContext(image.size)
    image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))

    let rect: CGRect = CGRectMake(pointof.x, pointof.y, image.size.width, image.size.height)


    text.drawInRect(CGRectIntegral(rect), withAttributes:attributeDict as [NSObject : AnyObject])

    let contxt:CGContextRef = UIGraphicsGetCurrentContext()

    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

但我认为这是一种 "messy" 的方式,尤其是由于某种原因字体大小与标签中的字体大小不匹配。

所以我的问题如下:有什么方法可以使我使用第一种方法得到的图像像素化程度降低吗?或者有什么更简单的方法可以达到我想要的效果吗?

我想要这个的原因是因为我有一个 UITextField,我可以在图像上写文本,但我想在图像上添加标签比文本字段更容易。

如有任何关于如何实现这一点的建议,我们将不胜感激。

您没有将比例因子考虑在内。使用

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,YES,0.0)

而不是

UIGraphicsBeginImageContext(self.view.bounds.size)

后者假定比例因子为 1,但几乎不再是这种情况,因为当前所有设备都具有视网膜显示器。

使用比真实比例因子更小的比例因子会导致图像更小,在视网膜屏幕上显示时看起来像素化。