自定义CustomOverlay:
.h
@interface CustomOverlay : NSObject<MKOverlay>
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, readonly) MKMapRect boundingMapRect;
- (id)initWithRect:(MKMapRect)rect;
@end
.m
@interface CustomOverlay ()
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
@property (nonatomic, readwrite) MKMapRect boundingMapRect;
@end
@implementation CustomOverlay
@synthesize coordinate = _coordinate;
@synthesize boundingMapRect = _boundingMapRect;
#pragma mark - Initalize
- (id)initWithRect:(MKMapRect)rect
{
if (self = [super init])
{
self.boundingMapRect = rect;
}
return self;
}
@end
自定义CustomOverlayRenderer:
继承MKOverlayRenderer
.m实现代码
@interface CustomOverlayRenderer ()
@property (nonatomic, strong) UIImage *image;
@end
@implementation CustomOverlayRenderer
- (id) initWithOverlay:(id)overlay{
self = [super initWithOverlay:overlay];
if (self){
self.image = [UIImage imageNamed:@"MapHiddenBG.png"];
}
return self;
}
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
@autoreleasepool {
CustomOverlay *overlay = (CustomOverlay *)self.overlay;
if (overlay == nil)
{
NSLog(@"overlay is nil");
return;
}
MKMapRect theMapRect = [self.overlay boundingMapRect];
CGRect theRect = [self rectForMapRect:theMapRect];
// 绘制image
CGImageRef imageReference = self.image.CGImage;
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0.0, -theRect.size.height);
CGContextDrawImage(context, theRect, imageReference);
}
}
vc中添加
/** * 画覆盖层 */
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id)overlay {
if([overlay isKindOfClass:[CustomOverlay class]]){
//遮挡地图图片
CustomOverlayRenderer *renderer = [[CustomOverlayRenderer alloc] initWithOverlay:overlay];
return renderer;
}
return nil;
}
//添加覆盖层
- (void)showOverlay {
[self.mapView removeOverlay:self.mapHiddenImageOverlay];
self.mapHiddenImageOverlay = nil;
//添加图片遮盖层
self.mapHiddenImageOverlay = [[CustomOverlay alloc] initWithRect:MKMapRectWorld];
/*
MKOverlayLevelAboveRoads = 0, //显示在路上 建筑名字会显示在覆盖层上方
MKOverlayLevelAboveLabels //显示在标签上
*/
[self.mapView addOverlay:self.mapHiddenImageOverlay level:0];
}
demo下载:https://github.com/zhangEnBin1010/MapHiddenImageOverlay