【问题标题】:Adding a UILabel to UIImage with renderInContext使用 renderInContext 将 UILabel 添加到 UIImage
【发布时间】:2015-04-16 03:27:27
【问题描述】:

长期以来,我一直在努力寻找将带有背景颜色的 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
}

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

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

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

任何关于如何实现这一目标的建议将不胜感激。

【问题讨论】:

    标签: ios swift uiimageview uitextfield uilabel


    【解决方案1】:

    您没有将比例因子计入帐户。使用

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

    而不是

    UIGraphicsBeginImageContext(self.view.bounds.size)
    

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

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

    【讨论】:

    • 如果这应该支持 iPhone 6plus,我是否需要使用 3.0 (3x) 而不是 2.0?
    • 对不起,我输错了参数值 :) 刚刚编辑了我的答案来修复它。您必须将 scale 参数设置为 0.0,这将导致该方法始终在所有设备中使用正确的比例因子。
    • 查看这个 Swift 扩展来做到这一点http://stackoverflow.com/a/33545910/517707
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多