自定義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實現(xiàn)代碼
@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