我前面写了篇文章讲解如何给图片添加文字水印,而如果想要添加图片类型的水印也很简单,只要把原来代码里添加文字的部分改成图片即可。
3,使用样例
1,效果图如下:
(在图片左上角添加了一个半透明的logo图片)
2,为方便使用,我们通过扩展UIImage类来实现添加图片水印功能
(水印图片透明度,位置,边距都可以设置)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
//--- UIImageExtension.swift --- 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 = CGRectMake (0, 0, waterMarkImage.size.width, 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 .drawInRect( CGRectMake (0, 0, imageSize.width, imageSize.height)) waterMarkImage.drawInRect(markFrame, blendMode: . Normal , alpha: alpha) let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext () UIGraphicsEndImageContext () return waterMarkedImage } } |
3,使用样例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import UIKit class ViewController : UIViewController { @IBOutlet weak var imageView: UIImageView ! override func viewDidLoad() { super .viewDidLoad() //给图片添加水印 imageView.image = UIImage (named: "bg" )? .waterMarkedImage( UIImage (named: "logo7" )!,corner: . TopLeft , margin: CGPoint (x: 20, y: 20), alpha:1) } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() } } |