[Xcode10 实际操作]九、实用进阶-(16)给图片添加水印效果

本文将演示如何截取屏幕画面,并将截取图片,存入系统相册。

在项目文件夹【DemoApp】上点击鼠标右键

->【New File】创建一个扩展文件->模板选择窗口:【Swift File】->【Next】

->【Save As】:ExtensionUIImage.swift->保存默认的存储位置点击【Create】

在【ExtensionUIImage.swift】添加一个针对UIImage类的扩展。

扩展可以向一个已有的类、结构体或枚举类型添加新功能,

包括在没有获取源代码的情况下,对类型进行功能扩展。

点击编辑代码文件【ExtensionUIImage.swift】

 1 import UIKit
 2 
 3 extension UIImage
 4 {
 5     //添加一个扩展方法,包括的参数:
 6     //1.水印图片
 7     //2.透明图
 8     //3.边距值
 9     //并返回一个添加水印后的图片
10     func addWaterMark(_ image:UIImage, opacity:CGFloat, margin:CGFloat) -> UIImage
11     {
12         //创建一个位置在(0,0),尺寸与水印图片相同的显示区域
13         let imgFrame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
14         
15         //水印图片将放置在原始图片的右下角,
16         //通过将原始图片的宽度,减去水印图片的宽度
17         //获得水印图片在水平方向的位置
18         let posX = self.size.width - imgFrame.size.width  - margin
19         //同理获得水印图片在垂直方向的位置
20         let posY = self.size.height - imgFrame.size.height - margin
21         //创建一个在目标位置上的显示区域,用来放置水印图片
22         let targetFrame = CGRect(x: posX,
23                                  y: posY, 
24                                  width: image.size.width,
25                                  height: image.size.height)
26         
27         //创建一个图片上下文,上下文的尺寸与原始图片的尺寸相同
28         UIGraphicsBeginImageContext(self.size)
29         
30         //首先将原始图片绘制在上下文中,并设置其位置在(0,0)
31         self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
32         //将水印图片,绘制在上下文中的目标位置
33         //设置图像混合模式为正常、并设置其透明度信息
34         image.draw(in: targetFrame, blendMode: .normal, alpha: opacity)
35         //从上下文中,获得最后的渲染图片
36         let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
37         
38         //关闭上下文环境,及时释放资源
39         UIGraphicsEndImageContext()
40         
41         //最后返回最终的渲染结果
42         return waterMarkedImage!
43     }
44 }

在项目导航区,打开视图控制器的代码文件【ViewController.swift】

现在调用上文的扩展方法,实现给图片添加水印的功能。

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
 8         
 9         //首先在资源文件夹中,加载一张图片资源
10         var sourceImage = UIImage(named: "Pic1")
11         //同样加载一张图片资源,作为水印图片
12         let waterMarkImage = UIImage(named: "lion")
13         //调用扩展方法,将原始图片和水印图片,渲染成最终效果
14         //并设置相关的透明度和边距信息
15         sourceImage = sourceImage!.addWaterMark(waterMarkImage!, opacity: 0.5, margin: 20)
16         //初始化一个图像视图,用来显示混合后的图片
17         let imageView = UIImageView(image: sourceImage)
18 
19         //将图像视图,添加到当前视图控制器的根视图
20         self.view.addSubview(imageView)
21     }
22     
23     override func didReceiveMemoryWarning() {
24         super.didReceiveMemoryWarning()
25         // Dispose of any resources that can be recreated.
26     }
27 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10090291.html