使用Metal處理完圖像想要獲取成UIimage,然后保存,Metal處理完的圖片大小特別大,需要縮小之后再保存,如果MTLTexture是metalView.currentDrawable?.texture 獲取的,需要將metalView.framebufferOnly 設置為false
//點擊事件保存圖片 @objc func getMetalImage(btn:UIButton){ if let texture = metalView.currentDrawable?.texture { metalView.removeFromSuperview() let imageview1 = UIImageView(frame: CGRect(x: 0, y: 100, width: 414, height: 500)) imageview1.image = mtlTextureToUIImage(texture: texture, wScale: imageRender.imageScale.0, hScale: imageRender.imageScale.1) imageview1.backgroundColor = .green imageview1.contentMode = .scaleAspectFit view.addSubview(imageview1) } } ///MTLTexture轉成UIimage, /// - Parameters: /// - texture: texture ,傳入的值如果是metalView.currentDrawable?.texture,需設置metalView.framebufferOnly = false /// - wScale: 寬度方向的有效圖像比例,用於剪切圖像 /// - hScale: 高度方向的有效圖像比例 /// - Returns: 返回UIimage func mtlTextureToUIImage(texture:MTLTexture,wScale:CGFloat,hScale:CGFloat) -> UIImage? { let ciimage = CIImage(mtlTexture: texture, options: nil) // let image = UIImage(ciImage: ciimage!)//直接獲取圖片太大且有空白 //剪切圖片 let croppedCiImage = ciimage?.cropped(to: CGRect(x: CGFloat(texture.width)/2 * (1 - wScale), y: CGFloat(texture.height)/2 * (1 - hScale), width: CGFloat(texture.width) * wScale, height: CGFloat(texture.height) * hScale)) metalView.removeFromSuperview() var uiimage12 = UIImage(ciImage: croppedCiImage!) let home = NSHomeDirectory() + "/Documents/image121.png" //存取一下,否則uiimage12.cgImage為nil try? uiimage12.pngData()?.write(to: URL(fileURLWithPath: home)) uiimage12 = UIImage(contentsOfFile: home)! //圖像寬高比 let aspectRatio = uiimage12.size.width/uiimage12.size.height //給定一個合適的大小尺寸,我取得是iPhone8Plus寬414 let size = CGSize(width: 414, height: 414 / aspectRatio) try? FileManager().removeItem(at: URL(string: home)!) //繪制圖片,因為圖片太大重新繪制(縮小) UIGraphicsBeginImageContext(size) //獲取context let context = UIGraphicsGetCurrentContext()! ///繪制 context.draw(uiimage12.cgImage!, in: CGRect(x:0 , y: 0, width: size.width, height: size.height)) //翻轉 context.translateBy(x: 0, y: -size.height) context.scaleBy(x: 1, y: -1) //獲取繪制的圖像 let image1 = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image1 }
