Search code examples
iosswiftcoordinatesxcode8uigraphicscontext

Extracting UI Image View coordinates


I'm currently creating a drawing based app, I would like there to be an option for the user to send the co-ordinates to another player.

I'm using swift3 in Xcode 8.1.

I am able to extract a PNG of the image but what I'd like to do is just send the coordinates in order to recreate the image on the other players screen.

I've posted the code to the user's drawing function. I did try to push ' context? ' into an array after ' addLine ' but nothing that looked like coordinates was pushed into the array.

func drawPicture(fromPoint:CGPoint, toPoint:CGPoint) {
   UIGraphicsBeginImageContextWithOptions(self.drawPage.bounds.size,       false, 0.0)
   drawPage.image?.draw(in: CGRect(x: 0, y:0, width:self.drawPage.bounds.width, height:self.drawPage.bounds.height))
   let context = UIGraphicsGetCurrentContext()

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

   context?.setBlendMode(CGBlendMode.color)
   context?.setLineCap(CGLineCap.round)
   context?.setLineWidth(5)
   context?.setStrokeColor(UIColor(red: 0.26, green: 0.53, blue: 0.96, alpha: 1.0).cgColor)

   context?.strokePath()

   drawPage.image = UIGraphicsGetImageFromCurrentImageContext()
   UIGraphicsEndImageContext()

   }

Thanks for any ideas you have :)


Solution

  • I would suggest adding an array in which you would add coordinates while you are drawing and then just send the content of that array wherever you need to. E.g. something like this:

    struct DrawingCoordinate {
            var from: CGPoint
            var to: CGPoint
            init(from: CGPoint, to: CGPoint) {
                self.from = from
                self.to = to
            }
        }
        var coordinatesArray = [DrawingCoordinate]()
    
        func drawPicture(fromPoint:CGPoint, toPoint:CGPoint) {
            UIGraphicsBeginImageContextWithOptions(self.drawPage.bounds.size,       false, 0.0)
            drawPage.image?.draw(in: CGRect(x: 0, y:0, width:self.drawPage.bounds.width, height:self.drawPage.bounds.height))
            let context = UIGraphicsGetCurrentContext()
    
            context?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
            context?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
    
            // add this line to your array
            coordinatesArray.append(DrawingCoordinate(from: fromPoint, to: toPoint))
    
            context?.setBlendMode(CGBlendMode.color)
            context?.setLineCap(CGLineCap.round)
            context?.setLineWidth(5)
            context?.setStrokeColor(UIColor(red: 0.26, green: 0.53, blue: 0.96, alpha: 1.0).cgColor)
    
            context?.strokePath()
    
            drawPage.image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }
    

    Does this make sense to you?