1,效果图如下:
(在图片左上角添加了一个半透明的logo图片)
2,为方便使用,我们通过扩展UIImage类来实现添加图片水印功能
(水印图片透明度,位置,边距都可以设置)
//--- UIImageExtension.swift ---
import UIKit
extension UIImage{
//水印位置枚举
enum WaterMarkCorner{
case TopLeft
case TopRight
case BottomLeft
case BottomRight
}
//添加图片水印方法
func waterMarkedImage(waterMarkImage:UIImage, corner:WaterMarkCorner = .BottomRight,
margin:CGPoint = CGPoint(x: 20, y: 20), alpha:CGFloat = 1) -> UIImage{
var markFrame = CGRect(x:0, y: 0, width:waterMarkImage.size.width,
height: waterMarkImage.size.height)
let imageSize = self.size
switch corner{
case .TopLeft:
markFrame.origin = margin
case .TopRight:
markFrame.origin = CGPoint(x: imageSize.width - waterMarkImage.size.width - margin.x,
y: margin.y)
case .BottomLeft:
markFrame.origin = CGPoint(x: margin.x,
y: imageSize.height - waterMarkImage.size.height - margin.y)
case .BottomRight:
markFrame.origin = CGPoint(x: imageSize.width - waterMarkImage.size.width - margin.x,
y: imageSize.height - waterMarkImage.size.height - margin.y)
}
// 开始给图片添加图片
UIGraphicsBeginImageContext(imageSize)
self.draw(in: CGRect(x: 0, y:0, width: imageSize.width, height: imageSize.height))
waterMarkImage.draw(in: markFrame, blendMode: .normal, alpha: alpha)
let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return waterMarkedImage!
}
}
3,使用样例
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
//给图片添加水印
imageView.image = UIImage(named:"bg")?
.waterMarkedImage(waterMarkImage: UIImage(named: "logo")!,
corner: .TopLeft,
margin: CGPoint(x: 20, y: 20), alpha:1)
}
}