È necessario evidenziare una forma irregolare quando l'utente tocca su di essa. La mia idea su come farlo era disegnare un poligono che corrisponda alla forma, riempirlo con un colore e cambiare l'opacità per renderlo traslucido. Purtroppo non riesco a trovare nulla su come farlo. Essenzialmente, voglio disegnare il poligono riempito, sovrapporlo alla mia mappa e quindi essere in grado di eliminarlo (o nasconderlo). Come posso realizzare questo?Disegno di poligoni in Swift
9
A
risposta
27
Probabilmente si desidera utilizzare uno CAShapeLayer
. Ecco una 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
Risultato:
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
+0
Perfetto! Esattamente quello che stavo cercando! Grazie! –
Vedi questa applicazione Mac scritto in Objective C. Si potrebbe ottenere un'idea da esso. – Sandeep
È possibile disegnare la forma in drawRect: (utilizzando UIBezierPath) oppure creare una vista e aggiungere un percorso di Bezier a un CAShapeLayer che si aggiunge al livello della vista. – rdelmar