作为打工人,难免会遇到需要外发身份证之类的情况用于租房之类的,为了防止别人那你的资料做非法用途,最好还是给图片打上水印,水印上标明用途。那么问题来了,怎么方便的给图片打上水印呢?
可惜我也没有找到答案,每次用 Photoshop 或者 Sketch 实在是太麻烦了,因为技术不精,每次调整样式也很麻烦。所以,作为一个 iOS 开发,当然是自己造一个啦~
GitHub - Yigang0622/Watermarker-iOS
这个 App 可以给一张图片进行平铺打水印,水印内容,透明度,字体大小,分散程度都是可以调节的,满足各种需求。
核心代码很简单,使用 UIGraphics 绘制水印,想要改功能的朋友直接Github 拉代码改吧。
private func addWaterMarkToImage(drawText: String, inImage: UIImage, atPoint: CGPoint) -> UIImage{
let imageWidth = inImage.cgImage?.width
let imageHeight = inImage.cgImage?.height
let textColor = watermarkConfiguration.watermarkColor.withAlphaComponent(self.opacity)
let textFont = UIFont(name: "Helvetica Bold", size: fontSize)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(inImage.size, false, scale)
let c = UIGraphicsGetCurrentContext()!
c.saveGState()
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
]
inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height))
c.translateBy(x: atPoint.x, y: atPoint.y)
c.rotate(by: -45 * .pi / 180)
var y = -imageHeight!
while y < imageHeight! * 2 {
var x = -imageWidth!
while x < imageWidth! * 2 {
let rect = CGRect(x: atPoint.x + CGFloat(x), y: atPoint.y + CGFloat(y), width: inImage.size.width, height: inImage.size.height)
drawText.draw(in: rect, withAttributes: textFontAttributes)
x += Int(drawText.width(font: textFont) + self.seperation)
}
y += Int(drawText.height(font: textFont) + self.seperation)
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
There are no comments