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?
Asked
Active
Viewed 1.7k times
15
-
See this mac app written in Objective C. You might get an idea from it. – Sandeep Nov 07 '14 at 20:47
-
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. – rdelmar Nov 07 '14 at 20:47
1 Answers
45
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:
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

Lukas
- 1,346
- 7
- 24
- 49

rob mayoff
- 375,296
- 67
- 796
- 848
-
thanks you man. It's great. Can you provide way to handle/add more line into path using drag function – famfamfam Aug 16 '18 at 13:36
-
how can we use pan gesture to move whole shape or one corner point to specific point ? – adijazz91 Aug 21 '20 at 08:17