I have a map custom view that inherit from MKOverlayPathView. I need this custom view to display circle, line and text.
I already managed to draw circle and line using path drawing CGPathAddArc and CGPathAddLineToPoint functions.
However, I still need to add text.
I tried to add text using
[text drawAtPoint:centerPoint withFont:font];
but I got invalid context error.
any idea?
Pushing the context with
UIGraphicsPushContext
generated a problem for me. Remind that the methoddrawMapRect:zoomScale:inContext:
is called from different threads in the same time so I had to synchronize the piece of code starting where theUIGraphicsPushContext
is called down toUIGraphicsPopContext
call.Also when calculating the font size like in
[UIFont systemFontOfSize:(5.0 * roadWidth)]
one should take into consideration the[UIScreen mainScreen].scale
, which for iPad, iPad2, iPhone3 is1
and for iPhone4 - 5 and iPad3 is2
. Otherwise the text size will be different from iPad2 to iPad3.So for me it ended like this:
[UIFont boldSystemFontOfSize:(6.0f * [UIScreen mainScreen].scale * roadWidth)]
With
MKOverlayPathView
, I think the easiest way to add text is to overridedrawMapRect:zoomScale:inContext:
and put the path and text drawing there (and do nothing in or don't implementcreatePath
).But if you're going to use
drawMapRect
anyway, you might want to just switch to subclassing a plainMKOverlayView
instead ofMKOverlayPathView
.With an
MKOverlayView
, override thedrawMapRect:zoomScale:inContext:
method and draw the circle usingCGContextAddArc
(orCGContextAddEllipseInRect
orCGPathAddArc
).You can draw the text using
drawAtPoint
in this method which will have the requiredcontext
.For example:
In relation to a comment in another answer...
When the center coordinate or radius (or whatever) of the associated
MKOverlay
changes, you can make theMKOverlayView
"move" by callingsetNeedsDisplayInMapRect:
on it (instead of removing and adding the overlay again). (When using aMKOverlayPathView
, you can callinvalidatePath
instead.)When calling
setNeedsDisplayInMapRect:
, you can pass theboundingMapRect
of the overlay for the map rect parameter.In the LocationReminders sample app from WWDC 2010, the overlay view uses KVO to observe changes to the associated
MKOverlay
and makes itself move whenever it detects a change to the circle's properties but you could monitor the changes in other ways and callsetNeedsDisplayInMapRect:
explicitly from outside the overlay view.(In a comment on another answer I did mention using
MKOverlayPathView
and that is how the LocationReminders app implements a moving circle overlay view. But I should have mentioned how you can also useMKOverlayView
to draw a circle. Sorry about that.)