如何创建图像叠加并添加到MKMapView? [英] How do I create an image overlay and add to MKMapView?

查看:75
本文介绍了如何创建图像叠加并添加到MKMapView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习MapKit,现在正在尝试添加图片作为地图视图的叠加层。
我似乎找不到任何示例代码来帮助解释如何做到这一点。

I am trying to learn MapKit and am now trying to add an image as an overlay to the map view. I can't seem to find any sample code to help explain how to do this.

你能帮我怎么创建 MKOverlay ,并将它们添加到 MKMapKit

Can you guys please help me how to create MKOverlays and add them to MKMapKit.

推荐答案

以下是一个如何将 UIImage MKMapView 覆盖。

Here is an example to how to sets a UIImage to a MKMapView overlay. Some parameter (coordinates and image path) are fixed, but the code can be easily changed, I guess.

创建一个符合 MKOverlay的类

MapOverlay.h

MapOverlay.h

@interface MapOverlay : NSObject <MKOverlay> {

}

- (MKMapRect)boundingMapRect;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

@end

MapOverlay.m

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的类:

Create an class that conforms to MKOverlayView:

MapOverlayView.h

MapOverlayView.h

@interface MapOverlayView : MKOverlayView {

}

@end

MapOverlayView.m

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:

Add the overlay to the MKMapView:

MapOverlay * mapOverlay = [[MapOverlay alloc] init];
[mapView addOverlay:mapOverlay];
[mapOverlay release];

在mapView代理上,实现viewForOverlay:

On the mapView delegate, implement the viewForOverlay:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {

    MapOverlay *mapOverlay = overlay;
    MapOverlayView *mapOverlayView = [[[MapOverlayView alloc] initWithOverlay:mapOverlay] autorelease];

    return mapOverlayView;

}

希望它有帮助!

这篇关于如何创建图像叠加并添加到MKMapView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆