Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Polygons in Swift

I need to highlight an irregular shape when the user taps on it. My idea on how to do it was to draw a polygon that matches the shape, fill it with a color and change the opacity to make it translucent. Unfortunately I can't find anything on how to do this. Essentially, I want to draw the filled polygon, overlay it on to my map and then be able to dismiss (or hide) it. How can I accomplish this?

like image 651
Floyd Resler Avatar asked Nov 07 '14 20:11

Floyd Resler


People also ask

How do you draw a polygon in Swift?

You can either draw the shape in drawRect: (using UIBezierPath), or create a view and add a bezier path to a CAShapeLayer that you add to the view's layer.


1 Answers

You probably want to use a CAShapeLayer. Here's a demo:

import XCPlayground
import UIKit
import CoreText

let view = UIView(frame: CGRectMake(0, 0, 300, 300))
XCPShowView("view", view)

let imageView = UIImageView(image: UIImage(named: "profile.jpg"))
imageView.frame = view.bounds
imageView.contentMode = UIViewContentMode.ScaleAspectFill
view.addSubview(imageView)

let shape = CAShapeLayer()
view.layer.addSublayer(shape)
shape.opacity = 0.5
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
shape.strokeColor = UIColor(hue: 0.786, saturation: 0.79, brightness: 0.53, alpha: 1.0).CGColor
shape.fillColor = UIColor(hue: 0.786, saturation: 0.15, brightness: 0.89, alpha: 1.0).CGColor

let path = UIBezierPath()
path.moveToPoint(CGPointMake(120, 20))
path.addLineToPoint(CGPointMake(230, 90))
path.addLineToPoint(CGPointMake(240, 250))
path.addLineToPoint(CGPointMake(40, 280))
path.addLineToPoint(CGPointMake(100, 150))
path.closePath()
shape.path = path.CGPath

Result:

demo

Swift 3:

let shape = CAShapeLayer()
cell.layer.addSublayer(shape)
shape.opacity = 0.5
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
shape.strokeColor = UIColor(hue: 0.786, saturation: 0.79, brightness: 0.53, alpha: 1.0).cgColor
shape.fillColor = UIColor(hue: 0.786, saturation: 0.15, brightness: 0.89, alpha: 1.0).cgColor

 let path = UIBezierPath()
 path.move(to: CGPoint(x: 120, y: 20))
 path.addLine(to: CGPoint(x: 230, y: 90))
 path.addLine(to: CGPoint(x: 240, y: 250))
 path.addLine(to: CGPoint(x: 100, y: 150))
 path.close()
 shape.path = path.cgPath
like image 144
rob mayoff Avatar answered Sep 28 '22 08:09

rob mayoff