新建个swift类,设置为UIImage的类别,UIImage对象调用该方法就返回添加水印之后的Image对象了
import Foundation
import UIKit
extension UIImage {
func drawTextInImage()->UIImage {
//开启图片上下文
UIGraphicsBeginImageContext(self.size)
//图形重绘
self.draw(in: CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height))
//水印文字属性
let att = [NSForegroundColorAttributeName:UIColor.red,NSFontAttributeName:UIFont.systemFont(ofSize: 60),NSBackgroundColorAttributeName:UIColor.green]
//水印文字大小
let text = NSString(string: "**集团")
let size = text.size(attributes: att)
//绘制文字
text.draw(in: CGRect.init(x: self.size.width-450, y: self.size.height-80, width: size.width, height: size.height), withAttributes: att)
//从当前上下文获取图片
let image = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()
return image!
}
}