// // WeChatSportViewModelss.swift // FireBoltt // // Created by lemo. on 2020/10/27. // Copyright © 2020 Sheldon. All rights reserved. // import UIKit import RxSwift class WeChatSportViewModelss: ViewModel, ViewModelType { struct Input { let saveQrCode: Observable } struct Output { let qrCodeImage: BehaviorRelay } func transform(input: Input) -> Output { // 获取二维码 let qrCodeImage = BehaviorRelay(value: nil) if let deviceInfo = UserDefaultsManagerFrieBoltt.getDeviceInfo() { SVProgressHUD.show() ProviderRequest(.wechatGetCode(deviceMac: deviceInfo.MACString)) .subscribe(onNext: { [weak self] json in SVProgressHUD.dismiss() if let url = json["data"].string { let image = self?.creatQrcode(url: url) qrCodeImage.accept(image) } }) .disposed(by: rx.disposeBag) } // 保存到相册 input.saveQrCode .subscribe(onNext: { [weak self] _ in if let image = qrCodeImage.value { SystemAuthorityFireBoltt.shared.getPhotoAuthority { [weak self] (result) in if result { // 保存图片至相册 UIImageWriteToSavedPhotosAlbum(image, self, nil, nil) SVProgressHUD.showSuccess(withStatus: MultiLanguageKey_FB.saveQrCodeSuccessFB.localized) } } } }) .disposed(by: rx.disposeBag) return Output(qrCodeImage: qrCodeImage) } private func creatQrcode(url: String) -> UIImage { /// CIFilter let filter = CIFilter.init(name: "CIQRCodeGenerator") filter?.setDefaults() /// Add Data let data = url.data(using: .utf8) filter?.setValue(data, forKeyPath: "inputMessage") /// Out Put let outputImage = filter?.outputImage /// Show QRCode return createUIImageFromCIImages(image: outputImage!, size: 200) } // 高清处理 private func createUIImageFromCIImages(image: CIImage, size: CGFloat) -> UIImage { let extent = image.extent.integral let scale = min(size / extent.width, size / extent.height) /// Create bitmap let width: size_t = size_t(extent.width * scale) let height: size_t = size_t(extent.height * scale) let cs: CGColorSpace = CGColorSpaceCreateDeviceGray() let bitmap: CGContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 1)! let context = CIContext.init() let bitmapImage = context.createCGImage(image, from: extent) bitmap.interpolationQuality = .none bitmap.scaleBy(x: scale, y: scale) bitmap.draw(bitmapImage!, in: extent) let scaledImage = bitmap.makeImage() return UIImage.init(cgImage: scaledImage!) } }