将文字转换成图片

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

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
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容