// // 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 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))) 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) } // 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 == nil { 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 { updateUserInteraction(true) updateProgress(0) 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.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 = nil 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?.initProgress() } } 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 } }