-
Notifications
You must be signed in to change notification settings - Fork 0
/
UIImage+Extension.swift
89 lines (62 loc) · 2.36 KB
/
UIImage+Extension.swift
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// UIImage+Extension.swift
//
// Created by Allan-Dev1 on 2017-05-13.
// Copyright © 2017 Allan. All rights reserved.
//
import UIKit
extension UIImage {
/// create circle image
///
/// - Parameters:
/// - size: size of image
/// - backColor: make the corner match the background color
/// - borderColor: border color
/// - hasBorder: set border or not
/// - Returns: UIImage
func roundedImage(size: CGSize?, backColor: UIColor = UIColor.white, borderColor: UIColor = UIColor.lightGray, hasBorder: Bool = true) -> UIImage? {
var size = size
if size == nil {
size = self.size
}
let rect = CGRect(origin: CGPoint(), size: size!)
UIGraphicsBeginImageContextWithOptions(size!, true, 0)
backColor.setFill()
UIRectFill(rect)
let path = UIBezierPath(ovalIn: rect)
path.addClip()
draw(in: rect)
if hasBorder {
let borderPath = UIBezierPath(ovalIn: rect)
borderPath.lineWidth = 2
borderColor.setStroke()
borderPath.stroke()
}
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
/// Resize image for better memory performance
///
/// - Parameter size: new size of the image
/// - Parameter backColor: background color of the image
/// - Parameter isTransparent: whether image has transparent background (like png)
// if yes, need to set the background color match superview's background
/// - Returns: UIImage
func image(size: CGSize? = nil, backColor: UIColor = UIColor.white, isTransparent: Bool = true) -> UIImage? {
var size = size
if size == nil {
size = self.size
}
let rect = CGRect(origin: CGPoint(), size: size!)
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
if isTransparent {
backColor.setFill()
UIRectFill(rect)
}
draw(in: rect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}