簡體   English   中英

如何從 swift 中的路徑剪切圖像

[英]How to Cut image from path in swift

我正在嘗試使用 UIBezierPath(用戶繪制路徑)裁剪圖像

    let originalImage = treaCameraImage!
    
    UIGraphicsBeginImageContext(originalImage.size)
    originalImage.draw(at: .zero)
    
    let context = UIGraphicsGetCurrentContext()
    context!.addPath(path.cgPath)
    context!.clip()
    context!.setFillColor(UIColor.red.cgColor)
    context!.clear(CGRect(x: 0, y: 0, width: originalImage.size.width, height: originalImage.size.width))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    imageCut.image = newImage

圖像1 圖2

對於您需要的解決方案,您首先需要在viewDidAppear中添加此代碼

 override func viewDidAppear(_ animated: Bool) {
    //Implemented to overcome trackerview problem(UIBreizerPath is not correct) when working direcly on an image bigger than the screen(For brackets cut image).
    if (self.treaCameraImage!.size.width != self.view.bounds.size.width || self.treaCameraImage!.size.height != self.view.bounds.size.width) {
        
        UIGraphicsBeginImageContext(self.imageCut.bounds.size);
       
        let context = UIGraphicsGetCurrentContext()
        if let context = context {
            imageCut.layer.render(in: context)
        }
        let screenShot = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext();
        self.treaCameraImage = screenShot;
        //self.tempOriginalImage = screenShot;
    }
}

treaCameraImage是默認圖像, imageCut是圖像容器

在我剪切圖像的方法中,我改變了:

context.:clear(CGRect(x, 0: y, 0: width. originalImage.size,width: height. originalImage.size.width))

對此:

context.:clear(CGRect(x, 0: y, 0: width. originalImage.size,width * 2: height. originalImage.size.width * 2))

這對我有用! 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM