且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将图像添加到MKPointAnnotation

更新时间:2023-12-06 16:28:40

您需要设置 MKMapViewDelegate ,并实现

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation

示例代码,这些代码是从Apple开发者网站上提供的MapCallouts示例代码中窃取的。我已经对其进行了修改,以使重点放在重要细节上。您可以在下面看到关键是将图像设置在注释视图上,然后从该方法返回该注释视图。

Here's sample code, stolen from the MapCallouts sample code provided on Apple's developer site. I've modified it to focus on the important details. You can see below that the key is to set the image on an annotation view, and return that annotation view from this method.

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
        static NSString *SFAnnotationIdentifier = @"SFAnnotationIdentifier";
        MKPinAnnotationView *pinView =
            (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:SFAnnotationIdentifier];
        if (!pinView)
        {
            MKAnnotationView *annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                           reuseIdentifier:SFAnnotationIdentifier] autorelease];
            UIImage *flagImage = [UIImage imageNamed:@"flag.png"];
            // You may need to resize the image here.
            annotationView.image = flagImage;
            return annotationView;
        }
        else
        {
            pinView.annotation = annotation;
        }
        return pinView;
}

我们使用dequeueReusableAnnotationViewWithIdentifier来获取已经创建的视图以重用批注视图。如果未退回,我们将创建一个新的。如果只有几个同时出现,这将阻止我们创建数百个MKAnnotationView。

We use dequeueReusableAnnotationViewWithIdentifier to grab an already created view to make reuse of our annotation views. If one isn't returned we create a new one. This prevents us from creating hundreds of MKAnnotationViews if only a few are ever in sight at the same time.