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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With