iphone - 如何创建图像叠加层并将其添加到 MKMapView?

标签 iphone cocoa-touch mkmapview

我正在尝试学习 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/

相关文章:

iphone - 向 MKMapView 添加未知数量的注释

iphone - 对 NSDictionary 的 NSArray 进行排序

iphone - 为什么 self.editing 和 self.tableView.editing 工作相同/正常?

iphone - 使用 NSUserDefaults 存储和调用用户坐标

iphone - 没有配件按钮的标注配件

ios - 使用 UICollectionViewFlowLayout/UICollectionViewLayout 子类,不会在正确的时间调用 CellForItemAtIndexPath

iphone - iOS KeyChain 不从后台检索值

iphone - iAD 不适用于 iOS 5.1 设备,但适用于 iOS 5.1 模拟器

iphone - 更改子类的方法名称

iphone - 为每个用户生成唯一的号码并对数据进行加密