• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift - 给图片添加图片水印(图片上绘制另一张图,并可设透明度) ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
我前面写了篇文章讲解如何给图片添加文字水印,而如果想要添加图片类型的水印也很简单,只要把原来代码里添加文字的部分改成图片即可。

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()
    }
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap