ios - Merge UIImage with UILabel into one UIImage, Swift
问题描述
I am trying to "merge" an UIImage with a UILabel into one UIImage, for that I wrote a function everything works fine except that the Label does not get added to the Current Graphics Context. I would appreciate your help!
func textToImage(drawText: String, inImage: UIImage, atPoint: CGPoint) -> UIImage{
// Setup the image context using the passed image
UIGraphicsBeginImageContext(inImage.size)
// Put the image into a rectangle as large as the original image
inImage.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: inImage.size.width, height: inImage.size.height)))
// Create a point within the space that is as bit as the image
let rectPos = CGPoint(x: atPoint.x, y: atPoint.y)
let rectSize = CGSize(width: inImage.size.width, height: inImage.size.height)
let rect = CGRect(origin: rectPos, size: rectSize)
// Draw the text into an image
let label = UILabel()
label.text = drawText
label.textColor = .white
label.font = UIFont(name: "Helvetica Bold", size: 12)!
label.drawText(in: rect)
// Create a new image out of the images we have created
let newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage!
}
解决方案
您的代码的问题是 UIKit(UILabel 用法)试图在自己的上下文中绘制内容。您需要在相同的上下文中绘制文本 + 图像以获得所需的结果。
试试这个来接收结果图像:
func textToImage(drawText text: NSString, inImage image: UIImage) -> UIImage
{
UIGraphicsBeginImageContext(image.size)
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
let font=UIFont(name: "Helvetica-Bold", size: 8)!
let paraStyle=NSMutableParagraphStyle()
paraStyle.alignment=NSTextAlignment.center
let attributes = [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:font, NSAttributedStringKey.paragraphStyle:paraStyle]
let height = font.lineHeight
let y = (image.size.height-height) / 2
let strRect = CGRect(x: 0, y: y, width: image.size.width, height: height)
text.draw(in: strRect.integral, withAttributes: attributes)
let result=UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
@IBAction func touchTest(_ sender: Any)
{
let button = sender as! UIButton
let image = self.textToImage(drawText: "my text", inImage: UIImage.init(named: "circle")!)
button.setBackgroundImage(image, for: UIControlState.normal)
}
推荐阅读
- python - 如何堆叠for循环的每次迭代的输出?
- windows - 在不重新启动 Windows 的情况下更新 KMDF 驱动程序
- php - 在 php 中收到 FormData 时导致错误
- raspberry-pi - 如何在树莓派上卸载motioneye?
- firebase - Crashlytics - Firebase 日志中的 Stacktrace 不可读
- react-native - Expo Audio保持ActiveInBackground不工作
- c++ - AVX2 SIMD Instrinsics 16 位到 8 位,反之亦然
- python - 这个答案的python 3版本是什么?
- java - 如何让程序等到计时器线程完成后再继续?
- javascript - 使用 Vanilla JavaScript 操作 SVG 路径坐标