有没有办法使用path图添加文本
我有一个从MKOverlayPathViewinheritance的地图自定义视图。 我需要这个自定义视图来显示圆形,线条和文字。
我已经设法使用path绘制CGPathAddArc和CGPathAddLineToPoint函数绘制圆和线。
不过,我仍然需要添加文字。
我试图使用添加文本
[text drawAtPoint:centerPoint withFont:font];
但我得到了无效的上下文错误。
任何想法?
使用MKOverlayPathView
,我认为最简单的添加文本的方法是覆盖drawMapRect:zoomScale:inContext:
并将path和文本绘制放在那里(并且不执行或不执行createPath
)。
但是,如果你打算使用drawMapRect
,你可能只想切换到一个普通的MKOverlayView
而不是MKOverlayPathView
。
使用MKOverlayView
,覆盖drawMapRect:zoomScale:inContext:
方法,并使用CGContextAddArc
(或CGContextAddEllipseInRect
或CGPathAddArc
)绘制圆。
您可以在此方法中使用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
的中心坐标或半径(或其他)发生变化时,可以通过调用setNeedsDisplayInMapRect:
来使MKOverlayView
“移动”(而不是再次移除和添加叠加层)。 (使用MKOverlayPathView
,您可以调用invalidatePath
。)
当调用setNeedsDisplayInMapRect:
,可以传递map rect参数的覆盖图的boundingMapRect
。
在WWDC 2010的LocationReminders示例应用程序中,覆盖视图使用KVO观察对关联MKOverlay
更改,并在检测到对该属性的更改时自动移动,但可以用其他方式监视更改并调用setNeedsDisplayInMapRect:
显式地从外部覆盖视图。
(在另外一个回答中,我提到了使用MKOverlayPathView
,LocationReminders应用程序实现了一个移动的圆形覆盖视图,但是我应该提到如何使用MKOverlayView
来绘制一个圆。
用UIGraphicsPushContext
推送上下文给我带来了一个问题。 提醒说drawMapRect:zoomScale:inContext:
是在不同的线程中同时调用的,所以我不得不将同一段代码从UIGraphicsPushContext
被调用的地方同步到UIGraphicsPopContext
调用。
另外,当计算字体大小像[UIFont systemFontOfSize:(5.0 * roadWidth)]
应该考虑[UIScreen mainScreen].scale
,对于iPad,iPad2,iPhone3是1
,对于[UIScreen mainScreen].scale
和iPad3是2
。 否则,文本大小将不同于iPad2到iPad3。
所以对我来说,它是这样结束: [UIFont boldSystemFontOfSize:(6.0f * [UIScreen mainScreen].scale * roadWidth)]