在 1 个函数中截取 2 个不同尺寸图像的屏幕截图

in 1 function take 2 screenshots of different size images

我希望下面的 swift 代码截取 2 个屏幕截图。一个屏幕截图应该是从顶部到 20% 的整个视图,另一个是从 20% 到 100% 的高度。我创建了一个图像来显示我正在寻找的东西。图片应该有不同的比例。我真的不知道还有什么要补充的。

var drawbox = Canvas()
 @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
}
 @objc func saving(){
     
            
            let vex = self.view.screenshot(for: drawbox.frame, clipToBounds: true)
            
            
            UIImageWriteToSavedPhotosAlbum(vex, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
        }
    
extension UIView {
    /// Takes a screenshot of a UIView, with an option to clip to view bounds and place a waterwark image
    /// - Parameter rect: offset and size of the screenshot to take
    /// - Parameter clipToBounds: Bool to check where self.bounds and rect intersect and adjust size so there is no empty space
    /// - Parameter watermark: UIImage of the watermark to place on top
    func screenshot(for rect: CGRect, clipToBounds: Bool = true, with watermark: UIImage? = nil) -> UIImage {
        var imageRect = rect
        if clipToBounds {
            imageRect = bounds.intersection(rect)
        }
        return UIGraphicsImageRenderer(bounds: imageRect).image { _ in
            drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
            watermark?.draw(in: CGRect(origin: imageRect.origin, size: CGSize(width: 32, height: 32))) // update origin to place watermark where you want, with this update it will place it in top left or screenshot.
        }
    }
}

图片保存后可以分割 我用这个功能把图片分割成两半 你可以改变比例

     extension UIImage {
     
    func topHalf(pers:CGFloat)-> UIImage? {
        guard let image = cgImage?
            .cropping(to: CGRect(origin: .zero,
                    size: CGSize(width: size.width * scale,
                                 height: (size.height * scale) * pers )))
        else { return nil }
        return UIImage(cgImage: image, scale: 1, orientation: imageOrientation)
    }
    func bottomHalf(pers:CGFloat)-> UIImage? {
        let scaledHight = (size.height * scale)
        guard let image = cgImage?
            .cropping(to: CGRect(origin: CGPoint(x: 0,
                                                 y: scaledHight - (scaledHight * pers).rounded()),
                                 size: CGSize(width: size.width * scale,
                                              height: scaledHight)))
        else {
            
            print("Null")
            
            return nil }
        return UIImage(cgImage: image)
    }
    
    func save(_ name: String) {
//            let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let path = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        
        let url = URL(fileURLWithPath: path.path).appendingPathComponent(name)
        try! self.pngData()?.write(to: url)
            print("saved image at \(url)")
        }
}

你可以这样使用它

let vex = self.view.screenshot(for:  self.view.frame, clipToBounds: true)
            vex .save("full.png") 
            let top = vex.topHalf(pers: 0.2)
            top?.save("Top.png")
            let bottom = vex.bottomHalf(pers: 0.8)
            bottom?.save("bottom.png")