在Swift中绘制多边形

时间:2014-11-07 20:43:12

标签: ios swift drawing polygons

当用户点击它时,我需要突出显示不规则的形状。我对如何做到这一点的想法是绘制一个与形状相匹配的多边形,用颜色填充它并改变不透明度使其变得半透明。不幸的是我找不到任何关于如何做到这一点。基本上,我想绘制填充多边形,将其叠加到我的地图上,然后能够解散(或隐藏)它。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:35)

您可能想要使用CAShapeLayer。这是一个演示:

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

结果:

demo

斯威夫特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