首先上效果:
Simulator Screen Shot - iPhone 11 - 2020-07-31 at 14.02.09.png
代碼
// 添加水印
extension UIImage {
func addWaterText(viewSize: CGSize, text: String, color: UIColor = .lightGray, font: UIFont = .systemFont(ofSize: 13)) -> UIImage? {
let scale = self.size.width/viewSize.width
// 計算text渲染大小
let sizeFont = UIFont.systemFont(ofSize: scale * font.pointSize)
// 計算text size width:.greatestFiniteMagnitude height:.greatestFiniteMagnitude
let textSize = text.hs_sizeWithConstrainedWidth(.greatestFiniteMagnitude, font: sizeFont)
//原始image的寬高
let viewWidth = self.size.width
let viewHeight = self.size.height
//進行尺寸重繪 為了防止圖片失真睦优,繪制區(qū)域?qū)捀吆驮紙D片寬高一樣
UIGraphicsBeginImageContext(self.size)
self.draw(in: CGRect.init(x: 0, y: 0, width: viewWidth, height: viewHeight))
//sqrtLength:原始image的對角線length据沈。在水印旋轉(zhuǎn)矩陣中只要矩陣的寬高是原始image的對角線長度腥泥,無論旋轉(zhuǎn)多少度都不會有空白简识。
let sqrtLength = CGFloat(sqrt(Double(viewWidth*viewWidth + viewHeight*viewHeight)))
let attr = [NSAttributedString.Key.font: sizeFont, NSAttributedString.Key.foregroundColor: color]
let attrStr = NSAttributedString.init(string: text, attributes: attr)
//繪制文字的寬高
let strWidth = textSize.width
let strHeight = textSize.height
//開始旋轉(zhuǎn)上下文矩陣,繪制水印文字
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: CGFloat(viewWidth/2), y: CGFloat(viewHeight/2))
context?.rotate(by: CGFloat(Double.pi / 16))
context?.translateBy(x: CGFloat(-viewWidth/2), y: CGFloat(-viewHeight/2))
//計算需要繪制的列數(shù)和行數(shù)
let VSpace:CGFloat = 50 * scale
let HSpace:CGFloat = 30 * scale
let horCount = Int(sqrtLength / (strWidth + HSpace) + 1)
let verCount = Int(sqrtLength / (strHeight + VSpace) + 1)
//此處計算出需要繪制水印文字的起始點颠毙,由于水印區(qū)域要大于圖片區(qū)域所以起點在原有基礎(chǔ)上移
let orignX = -(sqrtLength-viewWidth)/2
let orignY = -(sqrtLength-viewHeight)/2
//在每列繪制時X坐標疊加
var tempOrignX = orignX
//在每行繪制時Y坐標疊加
var tempOrignY = orignY
for i in 0...(horCount * verCount) {
attrStr.draw(in: CGRect.init(x: tempOrignX, y: tempOrignY, width: strWidth, height: strHeight))
if i % horCount == 0 && i != 0 {
tempOrignX = orignX
tempOrignY += strHeight + VSpace
} else {
tempOrignX += strWidth + HSpace
}
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
如何使用
var image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
image = image.addWaterText(viewSize: self.imageView.size, text: "僅供XXXX試用")!
self.imageView.image = image