如何优雅的给文件打水印

January 4, 2021
iOS开发

作为打工人,难免会遇到需要外发身份证之类的情况用于租房之类的,为了防止别人那你的资料做非法用途,最好还是给图片打上水印,水印上标明用途。那么问题来了,怎么方便的给图片打上水印呢?

可惜我也没有找到答案,每次用 Photoshop 或者 Sketch 实在是太麻烦了,因为技术不精,每次调整样式也很麻烦。所以,作为一个 iOS 开发,当然是自己造一个啦~
GitHub - Yigang0622/Watermarker-iOS

这个 App 可以给一张图片进行平铺打水印,水印内容,透明度,字体大小,分散程度都是可以调节的,满足各种需求。

核心代码很简单,使用 UIGraphics 绘制水印,想要改功能的朋友直接Github 拉代码改吧。

  1. private func addWaterMarkToImage(drawText: String, inImage: UIImage, atPoint: CGPoint) -> UIImage{
  2. let imageWidth = inImage.cgImage?.width
  3. let imageHeight = inImage.cgImage?.height
  4. let textColor = watermarkConfiguration.watermarkColor.withAlphaComponent(self.opacity)
  5. let textFont = UIFont(name: "Helvetica Bold", size: fontSize)!
  6. let scale = UIScreen.main.scale
  7. UIGraphicsBeginImageContextWithOptions(inImage.size, false, scale)
  8. let c = UIGraphicsGetCurrentContext()!
  9. c.saveGState()
  10. let textFontAttributes = [
  11. NSAttributedString.Key.font: textFont,
  12. NSAttributedString.Key.foregroundColor: textColor,
  13. ]
  14. inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height))
  15. c.translateBy(x: atPoint.x, y: atPoint.y)
  16. c.rotate(by: -45 * .pi / 180)
  17. var y = -imageHeight!
  18. while y < imageHeight! * 2 {
  19. var x = -imageWidth!
  20. while x < imageWidth! * 2 {
  21. let rect = CGRect(x: atPoint.x + CGFloat(x), y: atPoint.y + CGFloat(y), width: inImage.size.width, height: inImage.size.height)
  22. drawText.draw(in: rect, withAttributes: textFontAttributes)
  23. x += Int(drawText.width(font: textFont) + self.seperation)
  24. }
  25. y += Int(drawText.height(font: textFont) + self.seperation)
  26. }
  27. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  28. UIGraphicsEndImageContext()
  29. return newImage!
  30. }

Comments

作者
July 21, 2018 at 10:52 am

There are no comments

keyboard_arrow_up