在drawRect MKPolygonRenderer中写入文本

时间:2016-02-18 21:35:34

标签: swift text mapkit mkpolygonrenderer

好的,我的智慧结束了。我是MapKit的新手,并编写了一个健康统计应用程序,用于在MKMapView上绘制相对于患者居住地点的数据。我可以删除注释,并毫无问题地绘制邮政编码区域的多边形。

但是我想在地图多边形上写文字(而不是注释)。

这是我的代码,我已经将MKPolygonRender子类化为访问drawRect。

多边形是完美的,但没有文字。我已经尝试写入多边形中的第一个点(我最终会找到中心)

被困了几个晚上非常感激。

类PolygonRender:MKPolygonRenderer {     var point:CGPoint!

override init(overlay: MKOverlay) {
    super.init(overlay: overlay)
}

override func drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext) {


    super.drawMapRect(mapRect, zoomScale: zoomScale, inContext: context)
    let mapRect:MKMapRect = self.overlay.boundingMapRect
    let rect:CGRect = self.rectForMapRect(mapRect)
    UIGraphicsPushContext(context)
    var bPath = UIBezierPath()
    //let polygon:MKPolygon = self.polygon
    super.fillColor = UIColor.yellowColor()
    let points = self.polygon.points()
    let pointCount = self.polygon.pointCount

    var point:CGPoint = self.pointForMapPoint(points[0])
    bPath.moveToPoint(point)

    for var i = 1; i < pointCount; i++ {
        point = self.pointForMapPoint(points[i])
        bPath.addLineToPoint(point)

    }
    bPath.closePath()
    bPath.addClip()

    let roadWidth:CGFloat = MKRoadWidthAtZoomScale(zoomScale)

    let attributes: [String: AnyObject] = [
        NSForegroundColorAttributeName : UIColor.blackColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(5 * roadWidth)]


    let centerPoint = pointForMapPoint(points[0])
    print(centerPoint)
    let string:NSString = "Hello world"
    string.drawAtPoint(centerPoint, withAttributes: attributes)




    UIGraphicsPopContext()
}

1 个答案:

答案 0 :(得分:0)

一般来说,你做对了,但我认为字体太小,看不到文字。

尝试将字体大小设置为100或更大的值,以找出文本在那里,但您需要放大。

示例:

public override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {

    let rect:CGRect = self.rect(for: mapRect)

    UIGraphicsPushContext(context);

    // ...

    UIGraphicsPushContext(context);
    UIColor.black.setStroke()
    context.setLineWidth(1)
    context.stroke(rect.insetBy(dx: 0.5, dy: 0.5))

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center

    let attributes = [NSAttributedStringKey.paragraphStyle  : paragraphStyle,
                      NSAttributedStringKey.font            : UIFont.systemFont(ofSize: 100.0),
                      NSAttributedStringKey.foregroundColor : UIColor.black]
    "\(rect.size)".draw(in: rect, withAttributes: attributes)
    UIGraphicsPopContext();
}

下图显示当矩形尺寸为1024x1024时,地图上如何显示字体大小为100的文本

enter image description here