func getWaterMark(_ originalImage
: UIImage?,icon
:UIImage?, title
: String, andMark markFont
: UIFont, andMark markColor
: UIColor) -> UIImage? {
let HORIZONTAL_SPACE: CGFloat = 130
let VERTICAL_SPACE: CGFloat = 150
var font
: UIFont? = markFont
if font
== nil {
font
= UIFont.systemFont(ofSize
: 23)
}
var color
: UIColor? = markColor
if color
== nil {
color
= UIColor.blue
}
guard let viewWidth
= originalImage
?.size
.width
, let viewHeight
= originalImage
?.size
.height
else { return nil }
UIGraphicsBeginImageContext(CGSize(width
: viewWidth
, height
: viewHeight
))
originalImage
?.draw(in: CGRect(x
: 0, y
: 0, width
: viewWidth
, height
: viewHeight
))
let sqrtLength
= sqrt(viewWidth
* viewWidth
+ viewHeight
* viewHeight
)
let attrStr
= NSAttributedString(string
: title
, attributes
: [NSAttributedString.Key.foregroundColor
: markColor
, NSAttributedString.Key.font
: markFont
])
let strWidth
= attrStr
.size().width
let strHeight
= attrStr
.size().height
let context
= UIGraphicsGetCurrentContext()
context
?.concatenate(CGAffineTransform(translationX
: viewWidth
/ 2, y
: viewHeight
/ 2))
context
?.concatenate(CGAffineTransform(rotationAngle
: CGFloat(Double.pi
/ 7.0)))
context
?.concatenate(CGAffineTransform(translationX
: -viewWidth
/ 2, y
: -viewHeight
/ 2))
let horCount
: Int = Int(sqrtLength
/ CGFloat(strWidth
+ HORIZONTAL_SPACE)) + 1
let verCount
: Int = Int(sqrtLength
/ CGFloat(strHeight
+ VERTICAL_SPACE)) + 1
let orignX
: CGFloat = -(sqrtLength
- viewWidth
) / 2
let orignY
: CGFloat = -(sqrtLength
- viewHeight
) / 2
var tempOrignX
: CGFloat = orignX
var tempOrignY
: CGFloat = orignY
let iconW
= icon
!= nil ? strHeight
: 0
let iconL
= iconW
== 0 ? 0 : iconW
+ 5
for i
in 0..<horCount
* verCount
{
if icon
!= nil {
icon
?.draw(in: CGRect(x
: tempOrignX
, y
: tempOrignY
, width
: strHeight
, height
: strHeight
), blendMode
: CGBlendMode.hardLight
, alpha
: 0.9)
}
title
.draw(in: CGRect(x
: tempOrignX
+iconL
, y
: tempOrignY
, width
: strWidth
, height
: strHeight
), withAttributes
: [NSAttributedString.Key.foregroundColor
: markColor
, NSAttributedString.Key.font
: markFont
])
if i
% horCount
== 0 && i
!= 0 {
tempOrignX
= orignX
+ ( i
%2 == 0 ? (strWidth
+HORIZONTAL_SPACE)*0.5 : 0)
tempOrignY
+= strHeight
+ VERTICAL_SPACE
} else {
tempOrignX
+= strWidth
+ HORIZONTAL_SPACE
}
}
let finalImg
: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImg
}
借鉴博文
实现效果:
转载请注明原文地址: https://lol.8miu.com/read-36643.html