有没有一种方法来添加使用文本路径绘制有没有一种方法来添加使用文本路径绘制(Is there a wa

2019-05-14 00:28发布

我有一个从MKOverlayPathView继承地图自定义视图。 我需要这个自定义视图显示圆圈,线条和文字。

我已经使用管理路径绘制CGPathAddArc和CGPathAddLineToPoint功能绘制圆和直线。

不过,我仍然需要添加文本。

我尝试使用添加文本

 [text drawAtPoint:centerPoint withFont:font];

但我得到无效的情况下错误。

任何的想法?

Answer 1:

随着MKOverlayPathView ,我想添加文本的最简单的方法是重写drawMapRect:zoomScale:inContext:放路径和文本绘制有(什么都不做或没有实现createPath )。

但是,如果你要使用drawMapRect无论如何,你可能想要只需切换到子类普通MKOverlayView而不是MKOverlayPathView

MKOverlayView ,重写drawMapRect:zoomScale:inContext:方法和绘制使用圆CGContextAddArc (或CGContextAddEllipseInRectCGPathAddArc )。

您可以绘制使用文本drawAtPoint在这个方法中,将有需要的context

例如:

-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
    //calculate CG values from circle coordinate and radius...
    CLLocationCoordinate2D center = circle_overlay_center_coordinate_here;

    CGPoint centerPoint = 
        [self pointForMapPoint:MKMapPointForCoordinate(center)];

    CGFloat radius = MKMapPointsPerMeterAtLatitude(center.latitude) * 
                         circle_overlay_radius_here;

    CGFloat roadWidth = MKRoadWidthAtZoomScale(zoomScale);

    //draw the circle...
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextSetFillColorWithColor(context, [[UIColor blueColor] colorWithAlphaComponent:0.2].CGColor);
    CGContextSetLineWidth(context, roadWidth);
    CGContextAddArc(context, centerPoint.x, centerPoint.y, radius, 0, 2 * M_PI, true);
    CGContextDrawPath(context, kCGPathFillStroke);

    //draw the text...
    NSString *text = @"Hello";
    UIGraphicsPushContext(context);
    [[UIColor redColor] set];
    [text drawAtPoint:centerPoint 
             withFont:[UIFont systemFontOfSize:(5.0 * roadWidth)]];
    UIGraphicsPopContext();
}

关于在另一个答案评论...

当中心坐标或相关的半径(或其他) MKOverlay的变化,可以使MKOverlayView通过调用“动” setNeedsDisplayInMapRect:上(而不是删除并重新添加叠加)。 (当使用MKOverlayPathView ,您可以拨打invalidatePath代替。)

当调用setNeedsDisplayInMapRect:您可以通过boundingMapRect覆盖的地图rect参数的。

在从2010年WWDC的LocationReminders示例应用程序,覆盖视图使用志愿观察更改相关MKOverlay ,使自己移动时,它检测到改变为圆的属性,但你可以监视其他方面的变化并调用setNeedsDisplayInMapRect:从外部明确覆盖图。

(在另一个回答评论我没有使用提及MKOverlayPathView那就是LocationReminders应用程序如何实现运动圈覆盖图,但我应该提到如何你也可以使用MKOverlayView画一个圈。我们对此深感抱歉。)



Answer 2:

推进与上下文UIGraphicsPushContext产生我的问题。 提醒:该方法drawMapRect:zoomScale:inContext:从在同一时间不同的线程调用,所以我只好开始,其中的代码段同步UIGraphicsPushContext被称为下降到UIGraphicsPopContext通话。

还计算的字体大小等在时[UIFont systemFontOfSize:(5.0 * roadWidth)]应该考虑到[UIScreen mainScreen].scale ,其为iPad,iPad2的,iPhone3的是1和iPhone4的- 5和iPad3的是2 。 否则,文本大小将是iPad2的到iPad3的不同。

所以对我来说它结束这样的: [UIFont boldSystemFontOfSize:(6.0f * [UIScreen mainScreen].scale * roadWidth)]



文章来源: Is there a way to add text using Paths Drawing