如何创建一个将整个地图着色为某种颜色的叠加层?然后我需要能够在它上面放置注释.有任何想法吗?谢谢.
解决方法
你想要的是
MKOverlay和
MKOverlayView.
您可以在“相关示例代码”中提到的某个应用中找到Apple的代码.在上面的协议和类参考页面中.
您可以在“相关示例代码”中提到的某个应用中找到Apple的代码.在上面的协议和类参考页面中.
编辑:根据评论,以前的代码不能正常工作.这是一个MKMapDimOverlay GitHub项目,您可以使用CocoaPods进行集成.我还在答案中对以下代码进行了相关更改.
您需要创建叠加层并将其添加到地图视图中.
- MKMapDimOverlay *dimOverlay = [[MKMapDimOverlay alloc] initWithMapView:MapView];
- [mapView addOverlay: dimOverlay];
在’viewForOverlay’委托方法中为特定的MKOverlay创建并返回MKOverlayView
- -(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay {
- if([overlay isMemberOfClass:[MKMapDimOverlay class]]) {
- MKMapDimOverlayView *dimOverlayView = [[MKMapDimOverlayView alloc] initWithOverlay:overlay];
- return dimOverlayView;
- }
- }
由于您只需要覆盖地图的彩色叠加层,因此叠加层和叠加层视图的实现将非常简单.
DimOverlay.m
- @interface DimOverlay ()
- @property (nonatomic) CLLocationCoordinate2D dimOverlayCoordinates;
- @end
- @implementation DimOverlay
- -(id)initWithMapView:(MKMapView *)mapView {
- self = [super init];
- if(self)
- {
- self.dimOverlayCoordinates = mapView.centerCoordinate;
- }
- return self;
- }
- -(CLLocationCoordinate2D)coordinate {
- return self.dimOverlayCoordinates;
- }
- -(MKMapRect)boundingMapRect {
- return MKMapRectWorld;
- }
- @end
DimOverlayView.m
- @implementation DimOverlayView
- - (void)drawMapRect:(MKMapRect)mapRect
- zoomScale:(MKZoomScale)zoomScale
- inContext:(CGContextRef)ctx {
- /*
- You can allow custom colors and opacity values.
- Simply add UIColor and CGFloat properties in the overlay view class
- and use those properties instead of the default hardcodes values below.
- */
- CGContextSetAlpha(ctx,0.85);
- CGContextSetFillColorWithColor(ctx,[UIColor blackColor].CGColor);
- CGContextFillRect(ctx,[self rectForMapRect:mapRect]);
- }
- @end