Search code examples
ioshtmlswiftareacoords

Create clickable body diagram with Swift (iOS)


I'm trying to recreate something for a iOS app (Swift) which I already made in HTML5 (using map area-coords).

I want to show a human body diagram that interacts with user clicks/touches. The body exists of let's say 20 different parts, and the user can select one or more body-parts. For every body-part there is a selected-state image that should appear when a part is selected. Clicking on a selected part will deselect it. After selecting one or more parts, the user can continue and will get some information about these parts in a next viewcontroller. I am attaching a simplified image to explain my goal.

bodyparts selection

Can somebody explain what the best way is to achieve this goal? Is there a comparable technique that can be used in Swift to create such an interactive image?

Thanks!


Solution

  • Fixed!

    First I added sublayers to the UIImageView like this

    var path = UIBezierPath()
    path.moveToPoint(CGPointMake(20, 30))
    path.addLineToPoint(CGPointMake(40, 30))
    
    // add as many coordinates you need...
    
    path.closePath()
    
    var layer = CAShapeLayer()
    layer.path = path.CGPath
    layer.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.5).CGColor
    layer.hidden = true
    
    bodyImage.layer.addSublayer(layer)
    

    Than I overrided the touchesbegan function in order to show and hide when the shapes are tapped.

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
        if let touch = touches.first! as? UITouch {
            // get tapped position
            let position = touch.locationInView(self.bodyImage)
    
            // loop all sublayers
            for layer in self.bodyImage.layer.sublayers! as! [CAShapeLayer] {
    
                // check if tapped position is inside shape-path
                if CGPathContainsPoint(layer.path, nil, position, false) {
                    if (layer.hidden) {
                        layer.hidden = false
                    }
                    else {
                        layer.hidden = true
                    }
                }
            }
        }
    }