我是iOS新手,我的目标是使用Swift 3和MapKit在地图视图中添加自定义叠加层。我已经关注了Add inverted circle overlay to map view。 这是代码:
import UIKit
import MapKit
class MyMapOverlayRenderer: MKOverlayRenderer {
let diameter: Double
let fillColor: UIColor
init(overlay: MKOverlay, diameter: Double, fillColor: UIColor) {
self.diameter = diameter
self.fillColor = fillColor
super.init(overlay: overlay)
}
override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
let path = UIBezierPath(rect: CGRect(x: mapRect.origin.x, y: mapRect.origin.y, width: mapRect.size.width, height: mapRect.size.height))
path.usesEvenOddFillRule = true
let radiusInMapPoints = diameter * MKMapPointsPerMeterAtLatitude(self.overlay.coordinate.latitude)
let radiusSquared = MKMapSize(width: radiusInMapPoints, height: radiusInMapPoints)
let regionOrigin = MKMapPointForCoordinate(self.overlay.coordinate)
var regionRect = MKMapRect(origin: regionOrigin, size: radiusSquared)
regionRect = MKMapRectOffset(regionRect, -radiusInMapPoints / 2, -radiusInMapPoints / 2)
regionRect = MKMapRectIntersection(regionRect, MKMapRectWorld)
let cornerRadius = CGFloat(regionRect.size.width / Double(2))
let excludePath = UIBezierPath(roundedRect: CGRect(x: regionRect.origin.x, y: regionRect.origin.y, width: regionRect.size.width, height: regionRect.size.height), cornerRadius: cornerRadius)
path.append(excludePath)
context.setFillColor(fillColor.cgColor)
context.addPath(path.cgPath)
context.fillPath()
}
}
最终显示的叠加层没有排除路径(圆圈),是否有任何建议?
答案 0 :(得分:0)
解决了它,只是添加了reversing():
path.append(excludePath.reversing())
全功能代码:
override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
let path = UIBezierPath(rect: CGRect(x: mapRect.origin.x, y: mapRect.origin.y, width: mapRect.size.width, height: mapRect.size.height))
path.usesEvenOddFillRule = true
let radiusInMapPoints = diameter * MKMapPointsPerMeterAtLatitude(MKMapPointsPerMeterAtLatitude(overlay.coordinate.latitude))
let radiusSquared = MKMapSize(width: radiusInMapPoints, height: radiusInMapPoints)
let regionOrigin = MKMapPointForCoordinate(overlay.coordinate)
var regionRect = MKMapRect(origin: regionOrigin, size: radiusSquared)
regionRect = MKMapRectOffset(regionRect, -radiusInMapPoints / 2, -radiusInMapPoints / 2)
regionRect = MKMapRectIntersection(regionRect, MKMapRectWorld)
let midX = ( regionOrigin.x + regionRect.origin.x) / 2
let midY = ( regionOrigin.y + regionRect.origin.y) / 2
let cornerRadius = CGFloat(regionRect.size.width / Double(2))
let excludePath = UIBezierPath(roundedRect: CGRect(x: midX, y: midY, width: regionRect.size.width / 2, height: regionRect.size.height / 2), cornerRadius: cornerRadius)
path.append(excludePath.reversing())
context.setFillColor(fillColor.cgColor)
context.addPath(path.cgPath)
context.fillPath()
}