我正在尝试学习 MapKit,现在正在尝试将图像作为叠加层添加到 map View 中。 我似乎找不到任何示例代码来帮助解释如何执行此操作。
你们能帮助我如何创建 MKOverlay
并将它们添加到 MKMapKit
中吗?
提前致谢..
最佳答案
以下示例介绍了如何将 UIImage
设置为 MKMapView
叠加层。一些参数(坐标和图像路径)是固定的,但我猜代码可以很容易地改变。
创建一个符合MKOverlay
的类:
MapOverlay.h
@interface MapOverlay : NSObject <MKOverlay> {
}
- (MKMapRect)boundingMapRect;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@end
MapOverlay.m
@implementation MapOverlay
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate {
self = [super init];
if (self != nil) {
}
return self;
}
- (CLLocationCoordinate2D)coordinate
{
CLLocationCoordinate2D coord1 = {
37.434999,-122.16121
};
return coord1;
}
- (MKMapRect)boundingMapRect
{
MKMapPoint upperLeft = MKMapPointForCoordinate(self.coordinate);
MKMapRect bounds = MKMapRectMake(upperLeft.x, upperLeft.y, 2000, 2000);
return bounds;
}
@end
创建一个符合MKOverlayView的类:
MapOverlayView.h
@interface MapOverlayView : MKOverlayView {
}
@end
MapOverlayView.m
@implementation MapOverlayView
- (void)drawMapRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale
inContext:(CGContextRef)ctx
{
UIImage *image = [[UIImage imageNamed:@"image.png"] retain];
CGImageRef imageReference = image.CGImage;
MKMapRect theMapRect = [self.overlay boundingMapRect];
CGRect theRect = [self rectForMapRect:theMapRect];
CGRect clipRect = [self rectForMapRect:mapRect];
CGContextAddRect(ctx, clipRect);
CGContextClip(ctx);
CGContextDrawImage(ctx, theRect, imageReference);
[image release];
}
@end
将叠加层添加到 MKMapView:
MapOverlay * mapOverlay = [[MapOverlay alloc] init];
[mapView addOverlay:mapOverlay];
[mapOverlay release];
在mapView委托(delegate)上,实现viewForOverlay:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
MapOverlay *mapOverlay = overlay;
MapOverlayView *mapOverlayView = [[[MapOverlayView alloc] initWithOverlay:mapOverlay] autorelease];
return mapOverlayView;
}
希望对你有帮助!
关于iphone - 如何创建图像叠加层并将其添加到 MKMapView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5283741/