CustomDialViewController.swift
14.2 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
//
// CustomDialViewController.swift
// Twear
//
// Created by yangbin on 2022/1/20.
//
import UIKit
import MBProgressHUD
import Photos
import TZImagePickerController
import SwiftDate
class CustomDialViewController: UIViewController, TZImagePickerControllerDelegate {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout!
@IBOutlet weak var progressView: CustomProgress!
var picker: TZImagePickerController?
var imagePath = "custom"
@IBOutlet weak var imageView: UIImageView!
private var maxImageCount = 9
var imageArray: [UIImage] = []
var imageKeys: [String] = []
var curIndex: Int = 0
@IBOutlet weak var progressBottomLayout: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
// progressView.label.text = LocString("安装")
// progressView.label.textColor = UIColor.white
progressView.label.font = RegularFont(15)
// progressView.backView.backgroundColor = UIColor.rgbColorFromHex(0x00993E)
// progressView.layer.borderWidth = 1
// progressView.layer.borderColor = UIColor.rgbColorFromHex(0x00993E).cgColor
progressView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(sync)))
progressBottomLayout.constant = 80 + NAVBAR_HEIGHT
let imagesName = UIImage.getImagesName(path: imagePath).sorted()
if imagesName.count > 0 {
// curIndex = 1
initProgress()
imageKeys.append(contentsOf: imagesName)
for imageName in imagesName {
imageArray.append(UIImage.getImageFromPath(imageName, path: imagePath)!)
}
// imageView.image = imageArray[0]
} else {
initProgress(false)
}
self.imageView.image = UIImage(named: "custom_default")
// Do any additional setup after loading the view.
}
func configureCollectionView(){
collectionViewFlowLayout.scrollDirection = .horizontal
collectionViewFlowLayout.minimumLineSpacing = 10
collectionViewFlowLayout.minimumInteritemSpacing = 10
collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
collectionViewFlowLayout.itemSize = CGSize(width: 68.5, height: 80)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsVerticalScrollIndicator = false
collectionView.bounces = true
// self.automaticallyAdjustsScrollViewInsets = false
collectionView.register(UINib.init(nibName: "AddPictureCell", bundle: Bundle.main), forCellWithReuseIdentifier: "AddPictureCell")
}
@IBAction func sync() {
if IsDailSyncing { return }
if self.imageView.image == UIImage(named: "custom_default") {
return
}
let image = resizeImage(image: self.imageView.image!, targetSize: CGSize(width: 240, height: 280))
// let image = UIImage(contentsOfFile: "\(Bundle.main.resourcePath!)/test3.bmp")
// imageView.image = image
// let options: NSDictionary = [:]
// let convertToBmp = image.toData(options: options, type: .bmp)
// guard let bmpData = convertToBmp else {
// print("😡 ERROR: could not convert image to a bitmap bmpData var.")
// return
// }
// let data = UIImage(data: convertToBmp!)!.rbg565Data()!
// let b = [UInt8](data)
//
// for i in 0..<100 {
// print("\(i)--\(String(format: "%02X", b[i]))")
// }
// print(image.cgImage?.width)
// print(image.cgImage?.height)
// print(data.count)
if let imageData = image.rbg565Data(), imageData.count > 0 {
var bytes1 = [UInt8](imageData)
var bytes3 = Array(bytes1[198..<bytes1.count])
var bytes2: [UInt8] = [UInt8](repeating: 0, count: 198)//[186, 48, 0, 1, 0, 9, 65, 1, 4, 0, 51, 65, 0]
bytes2.append(contentsOf: bytes3)
// bytes3.append(contentsOf: bytes2)
var data1 = Data(bytes: bytes2, count: bytes2.count)
// self.imageView.image = UIImage(data: imageData)
var data11 = imageData
data11.append(data1)
updateUserInteraction(true)
updateProgress(0)
// return
BluetoothManager.shared.syncCustomDial(imageData) {[weak self] progress in
self?.updateProgress(progress)
} completion: {[weak self] error in
self?.updateUserInteraction(false)
if error == nil {
self?.updateProgress(100)
} else {
self?.initProgress()
self?.showAlert(title: LocString("提示"), message: LocString("安装失败,请重试"), cancelText: nil)
}
}
}
}
func updateProgress(_ value: Int) {
if value == 100 {
progressView.value = 100
progressView.trackView.backgroundColor = LineColor
progressView.layer.borderColor = LineColor.cgColor
progressView.layer.borderWidth = 0
progressView.label.text = LocString("安装完成")
progressView.label.textColor = .white
} else {
progressView.value = value
progressView.backView.backgroundColor = .white
progressView.trackView.backgroundColor = UIColor.rgbColorFromHex(0x64C876)
progressView.layer.borderWidth = 1
progressView.layer.borderColor = UIColor.rgbColorFromHex(0x00993E).cgColor
progressView.label.text = LocString("安装中...")
progressView.label.textColor = .black
}
}
func initProgress(_ bool: Bool = true) {
if bool {
progressView.backView.backgroundColor = TintColor
} else {
progressView.backView.backgroundColor = LineColor
}
progressView.value = 0
progressView.label.text = LocString("安装")
progressView.label.textColor = .white
progressView.layer.borderWidth = 0
}
private func addImages(_ images: [UIImage]) {
if IsDailSyncing {
MBProgressHUD.showh(LocString("正在推送表盘中,请稍后..."))
return
}
_ = MBProgressHUD.showMessage("")
DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
self.initProgress()
self.curIndex = self.imageArray.count+1
for image in images {
self.imageArray.append(image)
self.imageView.image = image
let key = Date().toString(.custom("MMddHHmmss"))
self.imageKeys.append(key)
_ = image.saveImageToPath(key, path: self.imagePath)
}
MBProgressHUD.hide()
self.collectionView.reloadData()
}
}
private func deleteImage(_ item: Int) {
if IsDailSyncing {
MBProgressHUD.showh(LocString("正在推送表盘中,请稍后..."))
return
}
let alertVC = UIAlertController(title: LocString("提示"), message: LocString("确定删除此背景吗?"), preferredStyle: .alert)
let confirm = UIAlertAction(title: LocString("确定"), style: .destructive) { [weak self] (action) in
if UIImage.deleteImage(name: (self?.imageKeys[item])!, path: (self?.imagePath)!) {
self?.imageArray.remove(at: item)
self?.imageKeys.remove(at: item)
}
if self?.imageArray.count == 0 {
self?.curIndex = 0
self?.imageView.image = UIImage(named: "custom_default")
self?.initProgress(false)
} else {
if self?.imageArray.count == item {
self?.curIndex = item
self?.imageView.image = self?.imageArray[item-1]
} else if item+1 == self?.curIndex {
self?.imageView.image = self?.imageArray[item]
} else {
self?.curIndex -= 1
}
self?.initProgress()
}
self?.collectionView.reloadData()
}
let cancel = UIAlertAction(title: LocString("取消"), style: .default, handler: nil)
alertVC.addAction(cancel)
alertVC.addAction(confirm)
present(alertVC, animated: true, completion: nil)
}
func updateUserInteraction(_ isSyncing: Bool) {
IsDailSyncing = isSyncing
let navController = navigationController as? ZCNavigationController
navController?.enableScreenEdgePanGestureRecognizer(!isSyncing)
}
private func photoAlbum() {
if PHPhotoLibrary.authorizationStatus().rawValue == 2 {
MBProgressHUD.show("请在“设置-隐私-照片“选项中,允许'HDF wear'访问你的照片")
return
}
// maxImageCount-imageArray.count
picker = TZImagePickerController(maxImagesCount: 1, columnNumber: 3, delegate: self)
picker?.modalPresentationStyle = .fullScreen
// picker?.allowPickingVideo = true
// if imageArray.count > 0 {
// if newsType == .image {
picker?.allowPickingVideo = false
// }
// }240 280
//视频
picker?.scaleAspectFillCrop = true
picker?.allowCameraLocation = false //位置
let cropWidth: CGFloat = SCREEN_WIDTH*0.65
let cropHeight: CGFloat = cropWidth*7/6
picker?.cropRect = CGRect(x: (SCREEN_WIDTH-cropWidth)/2, y: (SCREEN_HEIGHT-cropHeight)/2, width: cropWidth, height: cropHeight)
picker?.allowPickingGif = false //GIF
picker?.allowTakePicture = true //内部拍照
picker?.allowCrop = true //裁剪
picker?.didFinishPickingPhotosHandle = {[weak self] (photos, assets, isSelectOriginalPhoto) -> Void in
if let images = photos {
self?.addImages(images)
}
}
self.present(picker!, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
extension CustomDialViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if IsDailSyncing {
MBProgressHUD.showh(LocString("正在推送表盘中,请稍后..."))
return
}
if indexPath.row == 0 {
if imageArray.count <= maxImageCount {
photoAlbum()
} else {
MBProgressHUD.showh(LocString("最多只能添加9张图片"))
}
} else {
curIndex = indexPath.row
imageView.image = imageArray[indexPath.row-1]
collectionView.reloadData()
initProgress()
}
}
// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// return CGSize(width: 60, height: 80)
// }
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// if newsType == .video {
// maxImageCount = 1
// }
// if imageArray.count != maxImageCount {
return imageArray.count + 1
// }
// return maxImageCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: AddPictureCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddPictureCell", for: indexPath) as! AddPictureCell
// cell.backgroundColor =
var array = imageArray
array.insert(UIImage(named: "image_add")!, at: 0)
var keyArray = imageKeys
keyArray.insert("add", at: 0)
if indexPath.row == 0 {
cell.selectedImageView.isHidden = true
} else if indexPath.row == curIndex {
cell.selectedImageView.isHidden = false
} else {
cell.selectedImageView.isHidden = true
}
// array.append(UIImage(named: "image_add")!)
// if imageArray.count != maxImageCount {
cell.deleteBtn.isHidden = indexPath.row == 0//imageArray.count
// } else {
// cell.deleteBtn.isHidden = false
// }
cell.picture.image = array[indexPath.row]
cell.imageKey = keyArray[indexPath.row]
cell.deleteBtnBlock = {[weak self] in
self?.deleteImage(indexPath.row-1)
}
return cell
}
}