【发布时间】: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