// // 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 styleCollectionView: UICollectionView! @IBOutlet weak var styleCollectionViewFlowLayout: UICollectionViewFlowLayout! @IBOutlet weak var progressView: CustomProgress! var picker: TZImagePickerController? var imagePath = "custom" @IBOutlet weak var timeImageView: UIImageView! @IBOutlet weak var backgroundBtn: UIButton! @IBOutlet weak var styleBtn: UIButton! @IBOutlet weak var positionBtn: UIButton! @IBOutlet weak var backUnderLine: UIView! @IBOutlet weak var positionUnderLine: UIView! @IBOutlet weak var styleUnderLine: UIView! @IBOutlet weak var imageHeightLayout: NSLayoutConstraint! @IBOutlet weak var timeCenterY: NSLayoutConstraint! @IBOutlet weak var imageView: UIImageView! private var maxImageCount = 1000 var imageArray: [UIImage] = [] var imageKeys: [String] = [] var curIndex: Int = 0 var styleCellCount: Int = 4 var colorStyle: Int = 1 var positionStyle: Int = 0 var curStyle: Int = 0 // 1样式 2位置 var dialWidth: Int = 240 var dialHeight: Int = 280 var colorDic = ["橙": 0, "白": 1, "红": 6, "蓝": 3, "黄": 7, "绿": 5] var colorArray = ["橙", "白", "红", "蓝", "黄", "绿"] var user = UserInfo @IBOutlet weak var progressBottomLayout: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // if CurDevice.name.contains("Watch 8") { // dialWidth = 240 // dialHeight = 286 imageHeightLayout.constant = 180.0*CGFloat(dialHeight)/CGFloat(dialWidth) // } if CurDevice.name.contains("P8GT") { colorArray = ["橙", "白"] } configureCollectionView() progressView.label.font = RegularFont(15) progressView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(sync))) progressBottomLayout.constant = 25 + 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) } if user.customDial == "" { imageView.image = UIImage(named: "custom_default") } else { let customStyleArray = user.customDial.split(separator: "-") if customStyleArray.count == 3 { curIndex = Int(customStyleArray[0])! if curIndex > imageArray.count || curIndex == 0 { curIndex = 0 imageView.image = UIImage(named: "custom_default") } else { imageView.image = imageArray[curIndex-1] } colorStyle = Int(customStyleArray[1])! positionStyle = Int(customStyleArray[2])! timeImageView.image = UIImage(named: "dial_color_\(colorStyle)") timeCenterY = timeCenterY.setMultiplier(multiplier: CGFloat(positionStyle)*0.5+0.5) } } backgroundBtn.setTitle(LocString("背景"), for: .normal) styleBtn.setTitle(LocString("样式"), for: .normal) positionBtn.setTitle(LocString("位置"), for: .normal) // 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") styleCollectionViewFlowLayout.minimumLineSpacing = 25 styleCollectionViewFlowLayout.minimumInteritemSpacing = 10 styleCollectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) styleCollectionViewFlowLayout.itemSize = CGSize(width: (SCREEN_WIDTH-100.0)/4.0, height: (SCREEN_WIDTH-100.0)/24.0*7.0) styleCollectionView.delegate = self styleCollectionView.dataSource = self styleCollectionView.bounces = false styleCollectionView.register(UINib.init(nibName: "DialStyleCell", bundle: Bundle.main), forCellWithReuseIdentifier: "DialStyleCell") } func showAlert() -> Bool { if !DeviceIsConnected { IsDailSyncing = false self.showAlert(title: LocString("设备已断开"), message: "", cancelText: nil) {[weak self] action in self?.navigationController?.popToRootViewController(animated: true) } cancel: { _ in } return true } else { return false } } @IBAction func selectMode(_ sender: UIButton) { if IsDailSyncing { MBProgressHUD.showh(LocString("正在推送表盘中,请稍后...")) return } backgroundBtn.titleLabel?.font = RegularFont(15) styleBtn.titleLabel?.font = RegularFont(15) positionBtn.titleLabel?.font = RegularFont(15) backgroundBtn.setTitleColor(.black, for: .normal) styleBtn.setTitleColor(.black, for: .normal) positionBtn.setTitleColor(.black, for: .normal) backUnderLine.isHidden = true styleUnderLine.isHidden = true positionUnderLine.isHidden = true sender.titleLabel?.font = BoldFont(15) sender.setTitleColor(UIColor.rgbColorFromHex(0x00993E), for: .normal) curStyle = sender.tag switch sender.tag { case 0: backUnderLine.isHidden = false case 1: styleUnderLine.isHidden = false styleCellCount = colorArray.count styleCollectionView.reloadData() case 2: positionUnderLine.isHidden = false styleCellCount = 3 styleCollectionView.reloadData() default: break } collectionView.isHidden = sender.tag != 0 styleCollectionView.isHidden = sender.tag == 0 } @IBAction func sync() { if showAlert() { return } if IsDailSyncing { return } let image = resizeImage1(image: self.imageView.image!, targetSize: CGSize(width: dialWidth, height: dialHeight)) // if self.imageView.image == UIImage(named: "custom_default") { // image = resizeImage1(image: self.imageView.image!, targetSize: CGSize(width: dialWidth, height: dialHeight)) // } if let imageData = image.rbg565Data(), imageData.count > 0 { updateUserInteraction(true) updateProgress(0) BluetoothManager.shared.syncCustomDial(imageData, colorStyle: colorStyle, position: positionStyle) {[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 user.customDial = "\(curIndex)-\(colorStyle)-\(positionStyle)" AdminHelper.shared.updateUser(user) } 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 UIApplication.shared.isIdleTimerDisabled = isSyncing let navController = navigationController as? ZCNavigationController navController?.enableScreenEdgePanGestureRecognizer(!isSyncing) } deinit { print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!") } private func photoAlbum() { if PHPhotoLibrary.authorizationStatus().rawValue == 2 { MBProgressHUD.show("请在“设置-隐私-照片“选项中,允许'YTWatch'访问你的照片") 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*CGFloat(dialHeight)/CGFloat(dialWidth) 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 resizeImage1(image: UIImage, targetSize: CGSize) -> UIImage { // 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: targetSize.width, height: targetSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } 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 collectionView == self.collectionView { 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() } } else { if curStyle == 1 { //样式 colorStyle = colorDic[colorArray[indexPath.row]]! timeImageView.image = UIImage(named: "dial_color_\(colorStyle)") } else {//位置 positionStyle = indexPath.row timeCenterY = timeCenterY.setMultiplier(multiplier: CGFloat(positionStyle)*0.5+0.5) } initProgress() collectionView.reloadData() } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == self.collectionView { return imageArray.count + 1 } else { return styleCellCount } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.collectionView { let cell: AddPictureCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddPictureCell", for: indexPath) as! AddPictureCell 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 } cell.deleteBtn.isHidden = indexPath.row == 0//imageArray.count cell.picture.image = array[indexPath.row] cell.imageKey = keyArray[indexPath.row] cell.deleteBtnBlock = {[weak self] in self?.deleteImage(indexPath.row-1) } return cell } else { let cell: DialStyleCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DialStyleCell", for: indexPath) as! DialStyleCell if curIndex == 0 { cell.picture.image = UIImage(named: "custom_default") } else { cell.picture.image = imageArray[curIndex-1] } if curStyle == 1 { //样式 if colorDic[colorArray[indexPath.row]]! == colorStyle { cell.selectedImageView.isHidden = false } else { cell.selectedImageView.isHidden = true } cell.timeImageView.image = UIImage(named: "dial_color_\(colorDic[colorArray[indexPath.row]]!)") cell.timeCenterY = cell.timeCenterY.setMultiplier(multiplier: CGFloat(positionStyle)*0.5+0.5) } else { if indexPath.row == positionStyle { cell.selectedImageView.isHidden = false } else { cell.selectedImageView.isHidden = true } cell.timeImageView.image = UIImage(named: "dial_color_\(colorStyle)") cell.timeCenterY = cell.timeCenterY.setMultiplier(multiplier: CGFloat(indexPath.row)*0.5+0.5) } return cell } } }