Get a pixel precise image from CGPoints

44 Views Asked by At

I'm trying to make some kind of pencil signature view in my app, I did it with the help of this func:

 func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
           UIGraphicsBeginImageContext(canvasImageView.frame.size)
           guard let context = UIGraphicsGetCurrentContext() else {
             return
           }
           canvasImageView.image?.draw(in: canvasImageView.bounds)
           
           context.move(to: fromPoint)
           context.addLine(to: toPoint)
           
           context.setLineCap(.round)
           context.setBlendMode(.normal)
           context.setLineWidth(brushWidth)
           context.setStrokeColor(color.cgColor)
           
           context.strokePath()
           
           canvasImageView.image = UIGraphicsGetImageFromCurrentImageContext()
           canvasImageView.alpha = opacity
           
           UIGraphicsEndImageContext()
         }

and I'm keeping track of the actual touches and draw the lines with those functions:

   open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       guard let touch = touches.first else {
         return
       }
       swiped = false
       lastPoint = touch.location(in: canvasImageView)
       lines.append(lastPoint)
     }
     
     open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
       guard let touch = touches.first else {
         return
       }
       swiped = true
       let currentPoint = touch.location(in: canvasImageView)
       drawLine(from: lastPoint, to: currentPoint)
         lines.append(currentPoint)
       lastPoint = currentPoint
     }
     
     open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
       if !swiped {
         drawLine(from: lastPoint, to: lastPoint)
       }
         lines.append(lastPoint)

       UIGraphicsBeginImageContext(canvasImageView.frame.size)
         canvasImageView?.image?.draw(in: canvasImageView.bounds, blendMode: .normal, alpha: opacity)
         canvasImageView.image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
         
       
     }

What happens now is that I'm able to draw on the canvas image view and export a base64 representation of the image, The problem is that the exported base64 includes the transparent image view and the signature but I need only the signature, Which means that I need the exported image size to represent only the drawn signature meaning that the pixels will differ with every different signature, now it's fixed and it equals the dimensions of the canvas image view, How I can achieve something like that?

0

There are 0 best solutions below