-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSTScanView.swift
More file actions
418 lines (361 loc) · 13.8 KB
/
STScanView.swift
File metadata and controls
418 lines (361 loc) · 13.8 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//
// STScanView.swift
// STBaseProject
//
// Created by 寒江孤影 on 2018/3/14.
//
import UIKit
/// Safe-area adaptation toggle for `STScanView`.
public enum STSafeAreaAdaptation: Sendable, Equatable {
case enabled
case disabled
public var isEnabled: Bool { self == .enabled }
}
public struct STScanViewConfiguration {
public var scanAreaMargin: CGFloat = 60.0
public var scanLineHeight: CGFloat = 5.0
public var maskAlpha: CGFloat = 0.6
public var borderColor: UIColor = .white
public var cornerColor: UIColor = UIColor(red: 0.110, green: 0.659, blue: 0.894, alpha: 1.0)
public var cornerSize: CGSize = CGSize(width: 15.0, height: 15.0)
public var cornerLineWidth: CGFloat = 4.0
public var tipText: String = "将二维码放入框内,即可自动扫描"
public var tipTextColor: UIColor = .white
public var tipTextFont: UIFont = UIFont.systemFont(ofSize: 13)
public var animationDuration: TimeInterval = 1.5
public var animationInterval: TimeInterval = 0.3
public var automaticSafeAreaAdaptation: Bool = true
public init() {}
}
public enum STScanViewTheme {
case light
case dark
case custom(STScanViewConfiguration)
fileprivate var configuration: STScanViewConfiguration {
switch self {
case .light:
var config = STScanViewConfiguration()
config.maskAlpha = 0.4
config.borderColor = .black
config.tipTextColor = .black
return config
case .dark:
return STScanViewConfiguration()
case .custom(let config):
return config
}
}
}
public class STScanView: UIView {
// MARK: - Public Properties
public var scanType: STScanType = .qrCode {
didSet { updateScanType() }
}
public var theme: STScanViewTheme = .dark {
didSet {
configuration = theme.configuration
// configuration.didSet 已调用 setNeedsDisplay(),此处不需再次触发
}
}
public var configuration: STScanViewConfiguration = STScanViewConfiguration() {
didSet { updateConfiguration() }
}
public var isAnimating: Bool {
return !isAnimationStopped && scanType != .barCode
}
// MARK: - Private Properties
private var isAnimationStopped: Bool = false
private var heightScale: CGFloat = 1.0
private var animationStartWorkItem: DispatchWorkItem?
private var tipLabel: UILabel?
private var scanLineView: UIImageView?
// MARK: - Lifecycle
deinit {
stopAnimation()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
public override func layoutSubviews() {
super.layoutSubviews()
updateScanLineFrame()
updateTipLabelFrame()
}
public override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
if self.configuration.automaticSafeAreaAdaptation {
setNeedsDisplay()
setNeedsLayout()
}
}
// MARK: - Setup
private func setupView() {
backgroundColor = .clear
isAnimationStopped = false
setupScanLine()
setupTipLabel()
setupAccessibility()
}
private func setupScanLine() {
let view = UIImageView()
view.contentMode = .scaleToFill
view.image = makeScanLineImage()
view.alpha = 0
addSubview(view)
self.scanLineView = view
}
private func setupTipLabel() {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.layer.zPosition = 1
addSubview(label)
bringSubviewToFront(label)
self.tipLabel = label
updateTipLabelAppearance()
}
private func setupAccessibility() {
isAccessibilityElement = true
accessibilityTraits = .staticText
accessibilityLabel = "扫码区域"
accessibilityHint = self.configuration.tipText
}
// MARK: - Public Methods
public func st_configScanType(scanType: STScanType) {
self.scanType = scanType
}
public func st_startAnimating() {
startAnimation()
}
public func st_stopAnimating() {
stopAnimation()
}
// MARK: - Private Methods
private func updateScanType() {
switch self.scanType {
case .barCode:
heightScale = 3.0
stopAnimation()
case .qrCode, .all:
heightScale = 1.0
// 使用 DispatchWorkItem 以便在 scanType 快速切换时可取消旧的待执行动画
let item = DispatchWorkItem { [weak self] in
self?.startAnimation()
}
self.animationStartWorkItem = item
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: item)
}
setNeedsDisplay()
setNeedsLayout()
}
private func updateConfiguration() {
updateTipLabelAppearance()
updateScanLineImage()
setNeedsDisplay()
setupAccessibility()
}
private func updateTipLabelAppearance() {
self.tipLabel?.text = self.configuration.tipText
self.tipLabel?.textColor = self.configuration.tipTextColor
self.tipLabel?.font = self.configuration.tipTextFont
}
/// 每次按当前 configuration 重新生成扫描线图像,避免 lazy 缓存导致样式不跟随配置更新
private func makeScanLineImage() -> UIImage {
let size = CGSize(width: 1, height: self.configuration.scanLineHeight)
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image { ctx in
let colors = [UIColor.clear.cgColor,
self.configuration.cornerColor.cgColor,
UIColor.clear.cgColor] as CFArray
let locations: [CGFloat] = [0, 0.5, 1]
guard let gradient = CGGradient(
colorsSpace: CGColorSpaceCreateDeviceRGB(),
colors: colors,
locations: locations
) else { return }
ctx.cgContext.drawLinearGradient(
gradient,
start: .zero,
end: CGPoint(x: 0, y: size.height),
options: []
)
}
}
private func updateScanLineImage() {
self.scanLineView?.image = makeScanLineImage()
}
private func updateScanLineFrame() {
guard let scanLineView = self.scanLineView else { return }
let scanRect = calculateScanAreaRect()
let scanSize = calculateScanAreaSize()
scanLineView.frame = CGRect(
x: scanRect.minX + 2,
y: scanRect.minY + 2,
width: scanSize.width - 4,
height: self.configuration.scanLineHeight
)
}
private func updateTipLabelFrame() {
guard let tipLabel = self.tipLabel else { return }
let scanRect = calculateScanAreaRect()
tipLabel.frame = CGRect(
x: 0,
y: scanRect.maxY + 15,
width: bounds.width,
height: 50
)
}
private func startAnimation() {
guard self.scanType != .barCode && !isAnimationStopped else { return }
stopAnimation()
isAnimationStopped = false
guard let scanLineView = self.scanLineView else { return }
let scanRect = calculateScanAreaRect()
let startY = scanRect.minY + 2
let endY = scanRect.maxY - self.configuration.scanLineHeight - 2
var frame = scanLineView.frame
frame.origin.y = startY
scanLineView.frame = frame
scanLineView.alpha = 1.0
UIView.animate(
withDuration: self.configuration.animationDuration,
delay: 0,
options: [.curveEaseInOut],
animations: {
var newFrame = scanLineView.frame
newFrame.origin.y = endY
scanLineView.frame = newFrame
}
) { [weak self] _ in
guard let self, !self.isAnimationStopped else { return }
UIView.animate(withDuration: 0.2, animations: {
scanLineView.alpha = 0
}) { _ in
guard !self.isAnimationStopped else { return }
let item = DispatchWorkItem { [weak self] in
self?.startAnimation()
}
self.animationStartWorkItem = item
DispatchQueue.main.asyncAfter(deadline: .now() + self.configuration.animationInterval, execute: item)
}
}
}
private func stopAnimation() {
isAnimationStopped = true
self.animationStartWorkItem?.cancel()
self.animationStartWorkItem = nil
self.scanLineView?.layer.removeAllAnimations()
self.scanLineView?.alpha = 0
}
// MARK: - Drawing
public override func draw(_ rect: CGRect) {
super.draw(rect)
drawScanRect()
}
private func drawScanRect() {
guard let context = UIGraphicsGetCurrentContext() else { return }
let scanRect = calculateScanAreaRect()
drawMask(context: context, scanRect: scanRect)
drawBorder(context: context, scanRect: scanRect)
drawCorners(context: context, scanRect: scanRect)
}
private func calculateScanAreaSize() -> CGSize {
let margin = getEffectiveMargin()
let width = bounds.width - margin * 2
return CGSize(width: width, height: width / heightScale)
}
private func calculateScanAreaRect() -> CGRect {
let margin = getEffectiveMargin()
let scanSize = calculateScanAreaSize()
let x = margin
var y = bounds.height / 2.0 - scanSize.height / 2.0
if self.configuration.automaticSafeAreaAdaptation {
let safeAreaInsets = self.safeAreaInsets
let availableHeight = bounds.height - safeAreaInsets.top - safeAreaInsets.bottom
y = safeAreaInsets.top + (availableHeight - scanSize.height) / 2.0
}
return CGRect(x: x, y: y, width: scanSize.width, height: scanSize.height)
}
private func getEffectiveMargin() -> CGFloat {
var margin = self.configuration.scanAreaMargin / heightScale
if self.configuration.automaticSafeAreaAdaptation {
let safeAreaInsets = self.safeAreaInsets
margin = max(margin, safeAreaInsets.left + 20, safeAreaInsets.right + 20)
}
return margin
}
private func drawMask(context: CGContext, scanRect: CGRect) {
context.setFillColor(red: 0, green: 0, blue: 0, alpha: self.configuration.maskAlpha)
context.fill(CGRect(x: 0, y: 0, width: bounds.width, height: scanRect.minY))
context.fill(CGRect(x: 0, y: scanRect.minY, width: scanRect.minX, height: scanRect.height))
// 右侧宽度使用 bounds.width - scanRect.maxX,语义正确,不依赖左右对称假设
context.fill(CGRect(x: scanRect.maxX, y: scanRect.minY, width: bounds.width - scanRect.maxX, height: scanRect.height))
context.fill(CGRect(x: 0, y: scanRect.maxY, width: bounds.width, height: bounds.height - scanRect.maxY))
}
private func drawBorder(context: CGContext, scanRect: CGRect) {
context.setStrokeColor(self.configuration.borderColor.cgColor)
context.setLineWidth(1.0)
context.addRect(scanRect)
context.strokePath()
}
private func drawCorners(context: CGContext, scanRect: CGRect) {
context.setStrokeColor(self.configuration.cornerColor.cgColor)
context.setLineWidth(self.configuration.cornerLineWidth)
let cornerSize = self.configuration.cornerSize
let lineWidth = self.configuration.cornerLineWidth
let offset = lineWidth / 3.0
let points: [(CGPoint, [(CGFloat, CGFloat)])] = [
(CGPoint(x: scanRect.minX - offset, y: scanRect.minY - offset),
[(0, -lineWidth/2), (cornerSize.width, 0), (0, cornerSize.height)]),
(CGPoint(x: scanRect.maxX + offset, y: scanRect.minY - offset),
[(0, -lineWidth/2), (-cornerSize.width, 0), (0, cornerSize.height)]),
(CGPoint(x: scanRect.minX - offset, y: scanRect.maxY + offset),
[(0, lineWidth/2), (cornerSize.width, 0), (0, -cornerSize.height)]),
(CGPoint(x: scanRect.maxX + offset, y: scanRect.maxY + offset),
[(0, lineWidth/2), (-cornerSize.width, 0), (0, -cornerSize.height)])
]
for (startPoint, offsets) in points {
context.move(to: CGPoint(x: startPoint.x + offsets[0].0, y: startPoint.y + offsets[0].1))
context.addLine(to: CGPoint(x: startPoint.x + offsets[1].0, y: startPoint.y + offsets[1].1))
context.move(to: startPoint)
context.addLine(to: CGPoint(x: startPoint.x + offsets[2].0, y: startPoint.y + offsets[2].1))
}
context.strokePath()
}
}
// MARK: - Convenience Initializers
extension STScanView {
public convenience init(frame: CGRect, theme: STScanViewTheme) {
self.init(frame: frame)
self.theme = theme
}
public convenience init(frame: CGRect, configuration: STScanViewConfiguration) {
self.init(frame: frame)
self.configuration = configuration
}
}
// MARK: - Additional Public APIs
extension STScanView {
public func updateTipText(_ text: String) {
self.configuration.tipText = text
self.tipLabel?.text = text
setupAccessibility()
}
public func setSafeAreaAdaptation(_ adaptation: STSafeAreaAdaptation) {
self.configuration.automaticSafeAreaAdaptation = adaptation.isEnabled
setNeedsDisplay()
setNeedsLayout()
}
public func getScanAreaRect() -> CGRect {
return calculateScanAreaRect()
}
public func resetToDefault() {
self.theme = .dark
self.scanType = .qrCode
}
}