我们在实际项目中有需求要将文字转换成图片,这里提供一个协议,即可实现文字--->图片的转换。
protocol StringTransFormImage { }
func transformImage(with title: String, font: UIFont = UIFont.systemFont(ofSize: 17)) {
let text = title as NSString
let size = bounds.size
let textSize: CGSize = text.boundingRect(with: CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine], attributes: [.font : font], context: nil).size
let rect = CGRect(x: (size.width - textSize.width) / 2, y: (size.height - textSize.height) / 2, width: textSize.width, height: textSize.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context = UIGraphicsGetCurrentContext()
UIColor.gray.set()
context?.fill(rect)
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center // 文字居中
let attributes = [NSAttributedString.Key.font : font, .foregroundColor : UIColor.white, .paragraphStyle : paragraph]
text.draw(in: rect, withAttributes: attributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.image = newImage
}
网友评论