This repository has been archived by the owner on Nov 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSmoothView.swift
71 lines (60 loc) · 2.19 KB
/
SmoothView.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
//
// SmoothView.swift
// SmoothCorners
//
// Created by Felix Lapalme on 2019-03-24.
// Copyright © 2019 Felix Lapalme. All rights reserved.
//
import UIKit
class SmoothView: UIView {
private var flx_lastSetRadius : CGFloat = 0
private var flx_smoothMask : CAShapeLayer?
var flx_smoothCorners: Bool = false {
didSet {
updateMaskIfNeeded()
}
}
override func layoutSubviews() {
super.layoutSubviews()
if (flx_continuousCorners) {
updateMaskIfNeeded()
}
}
func updateMaskIfNeeded() {
if (flx_smoothCorners) {
if let maskBounds = flx_smoothMask?.path?.boundingBoxOfPath {
if (!bounds.equalTo(maskBounds)
|| flx_lastSetRadius != layer.cornerRadius) {
updateMaskShape()
}
} else {
let path = UIBezierPath(roundedRect: bounds,
cornerRadius: layer.cornerRadius)
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
flx_smoothMask = mask
flx_lastSetRadius = layer.cornerRadius
layer.addObserver(self,
forKeyPath: NSStringFromSelector(#selector(getter: CALayer.cornerRadius)),
options: [],
context: nil)
}
}
else if (flx_smoothMask != nil) {
layer.mask = nil
flx_smoothMask = nil
layer.removeObserver(self, forKeyPath: NSStringFromSelector(#selector(getter: CALayer.cornerRadius)))
}
}
func updateMaskShape() {
flx_smoothMask?.path = UIBezierPath(roundedRect: bounds,
cornerRadius: layer.cornerRadius).cgPath
flx_lastSetRadius = layer.cornerRadius
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == NSStringFromSelector(#selector(getter: CALayer.cornerRadius))) {
updateMaskIfNeeded()
}
}
}