iOS 原生地圖添加圖片覆蓋層

自定義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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容