很遗憾,您还不能在 iOS 的 GMSPolygon 中打洞,此功能仅适用于 Android。
解决方法是使用GMSProjection 类中的pointForCoordinate() 方法。此方法可以将地球坐标转换为应用程序窗口中的一个点。
另外,为了使孔透明,您可能需要在视图中使用CAShapeLayer。您可以在此StackOverflow answer 中查看更多详细信息。
示例代码:
class ViewController: UIViewController, GMSMapViewDelegate {
var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.cameraWithLatitude(-33.86,
longitude: 151.20, zoom: 10)
mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
self.view = mapView
self.mapView.delegate = self
}
func mapView(mapView: GMSMapView!, didChangeCameraPosition position: GMSCameraPosition!) {
let point = mapView.projection.pointForCoordinate(CLLocationCoordinate2DMake(-33.86, 151.20))
print("the screen point: \(point.x) \(point.y)")
for subview in view.subviews {
if subview.tag == 1 {
subview.layer.mask = nil
createHole(subview, holeX: point.x, holeY: point.y, radius: 100)
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let overlayView = UIView(frame: view.bounds)
overlayView.tag = 1
overlayView.alpha = 0.6
overlayView.backgroundColor = UIColor.blackColor()
overlayView.userInteractionEnabled = false
self.view.addSubview(overlayView)
}
func createHole(overlayView : UIView, holeX : CGFloat, holeY : CGFloat, radius: CGFloat)
{
let maskLayer = CAShapeLayer()
// Create a path with the rectangle in it.
let path = CGPathCreateMutable()
CGPathAddArc(path, nil, holeX, holeY, radius, 0.0, 2 * 3.14, false)
CGPathAddRect(path, nil, CGRectMake(0, 0, overlayView.frame.width, overlayView.frame.height))
maskLayer.backgroundColor = UIColor.blackColor().CGColor
maskLayer.path = path;
maskLayer.fillRule = kCAFillRuleEvenOdd
overlayView.layer.mask = maskLayer
overlayView.clipsToBounds = true
}
}