Draw a line realtime with Swift 3.0

前端 未结 1 2019
抹茶落季
抹茶落季 2020-12-17 02:03

I\'am trying to draw on a UIImageView. With Swift 1.2 I was able to get it to work, but I had to convert it to swift 3.0 and I just can\'t get it to work.

What it ne

相关标签:
1条回答
  • 2020-12-17 02:14

    You have to begin the image context:

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
    

    You also have to stroke the path:

    context?.strokePath()
    

    You also are not drawing the previous image:

    imageView.image?.draw(in: view.bounds)
    

    Thus:

    func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
    
        imageView.image?.draw(in: view.bounds)
    
        let context = UIGraphicsGetCurrentContext()
    
        context?.move(to: fromPoint)
        context?.addLine(to: toPoint)
    
        context?.setLineCap(CGLineCap.round)
        context?.setLineWidth(brushWidth)
        context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
        context?.setBlendMode(CGBlendMode.normal)
        context?.strokePath()
    
        imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        imageView.alpha = opacity
        UIGraphicsEndImageContext()
    }
    
    0 讨论(0)
提交回复
热议问题