美文网首页
将文字转换成图片

将文字转换成图片

作者: yyyyy先生 | 来源:发表于2021-12-06 09:12 被阅读0次

    我们在实际项目中有需求要将文字转换成图片,这里提供一个协议,即可实现文字--->图片的转换。

    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
        }
    

    相关文章

      网友评论

          本文标题:将文字转换成图片

          本文链接:https://www.haomeiwen.com/subject/ranrrltx.html