3

I'm trying make an eraser function in a project. I can draw the lines ok, but there is no action when I invoke CGBlendMode.clear.

Can anyone see what I'm doing wrong or missing. I'm posting a code snippet below, but if another piece is required, please let me know.

fileprivate func drawLine(_ stroke: Stroke) -> Void {
        print(#function)
        let properties = stroke.settings
        let array = stroke.points

        if array?.count == 1 {

            let pointStr = array?[0]
            let point = CGPointFromString(pointStr!)
            self.drawLineFrom(point, toPoint: point, properties: properties!)
        }

        for i in 0 ..< (array?.count)! - 1 {
            let pointStr0 = array?[i]
            let pointStr1 = array?[i+1]

            let point0 = CGPointFromString(pointStr0!)
            let point1 = CGPointFromString(pointStr1!)
            self.drawLineFrom(point0, toPoint: point1, properties: properties!)
        }
        self.mergeViews()
    }



    fileprivate func drawLineFrom(_ fromPoint: CGPoint, toPoint: CGPoint, properties: StrokeSettings) -> Void {
        print(#function)

        UIGraphicsBeginImageContext(self.frame.size)
        let context = UIGraphicsGetCurrentContext()

        context!.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
        context!.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))

        context!.setLineCap(CGLineCap.round)
        context!.setLineWidth(properties.width)

        print(#function, "drawEraseSwitch: ", drawEraseSwitch)
        if drawEraseSwitch == 0 {
            context!.setBlendMode(CGBlendMode.normal)
            context!.setStrokeColor(red: properties.color.red, green: properties.color.green, blue: properties.color.blue, alpha: 1.0)
        } else {
            context!.setStrokeColor(red: properties.color.red, green: properties.color.green, blue: properties.color.blue, alpha: 1.0)
            context!.setBlendMode(CGBlendMode.clear)
        }


        context!.strokePath()

        self.backgroundImageView.image?.draw(in: self.backgroundImageView.frame)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        self.backgroundImageView.image = image
        self.backgroundImageView.alpha = properties.color.alpha
        UIGraphicsEndImageContext()

    }





fileprivate func mergeViews() {
    print(#function)
    UIGraphicsBeginImageContext(self.mainImageView.frame.size)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    self.mainImageView.image = image
    UIGraphicsEndImageContext()

    //self.backgroundImageView.image = nil
}
ICL1901
  • 7,632
  • 14
  • 90
  • 138

0 Answers0