ios - 使用 renderInContext 添加 UILabel 到 UIImage

标签 ios swift uiimageview uitextfield uilabel

长期以来,我一直在努力寻找将带有背景颜色的 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,我可以在图像上写文本,但我想在图像上添加标签比文本字段更容易。

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

最佳答案

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

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

代替

UIGraphicsBeginImageContext(self.view.bounds.size)

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

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

关于ios - 使用 renderInContext 添加 UILabel 到 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28527537/

相关文章:

ios - 在 UIView 中使用 UIImagePickerController

iphone - 动画旋转 UIImageView

ios - 加载 UITableView 后停止事件指示器

ios - 使用 [FBSession openActiveSessionWithPublishPermissions : . 时出错。]

swift - iOS 9 消除了 MKDirectionsRequest 属性 "source"。如何处理?

ios - 为什么 SwiftUI View 模型应该用 @MainActor 注释?

iphone - 指定单元格 imageView 的宽度

objective-c - 在iPhone应用程序中存储500个NSString的数组

ios - NSRunLoop 有时会使应用程序无响应

ios - 如何从游戏场景中调用一个 Action