我想在 MKMapview 中添加一个 UIImage。
即:一个特定的位置,我想添加一个名为“apple.jpg”的图像。
我不知道该怎么做。
因为我已经添加了一个可拖动的图钉作为注释。但我不知道我是否可以添加多个图像。
要将图像添加为 MKMapView 的一部分,请参阅本教程...
并将图像添加为 MapView 上的 Pin 然后使用下面的代码...
MKAnnotationView *annotationView = [[[MKAnnotationView alloc] init];
annotationView.image = [UIImage imageNamed:@"apple.png"];
annotationView.annotation = annotation;
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annotationView.rightCalloutAccessoryView.tag = 101;
annotationView.canShowCallout = YES;
[yourMapView addAnnotation:annotationView];
正如@Kassem Bagher 提到的,您需要创建自定义MKAnnotationView
,检查任何教程(示例)
您的图像必须为 png 格式,请参见下面的代码。
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"pinView"];
if (!pinView) {
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"pinView"] autorelease];
pinView.image = [UIImage imageNamed:@"apple.png"];
pinView.canShowCallout = YES;
}
}
这是工作代码,我已经完成了下面的代码,没有必要的图像是 .png 、 .jpg 或 .gif 它是您可以使用的任何格式
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
MKPinAnnotationView *pinAnnotation = nil;
NSString *defaultPinID = @"myPin";
pinAnnotation = (MKPinAnnotationView *)[mapview dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinAnnotation == nil )
pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinAnnotation.image = [UIImage imageNamed:@"marker_postoffice.png"];
pinAnnotation.annotation = annotation;
pinAnnotation.canShowCallout = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[infoButton addTarget:self action:@selector(showDetails)forControlEvents:UIControlEventTouchUpInside];
pinAnnotation.rightCalloutAccessoryView = infoButton;
// now you can set diff image by [annotation title] you can set diff image with if else condition like below code
if([[annotation title] isEqualToString:objAppDelegate.OfficePinTitle])
{
pinAnnotation.image = [UIImage imageNamed:@"marker_postoffice.png"];
pinAnnotation.annotation = annotation;
pinAnnotation.canShowCallout = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
infoButton addTarget:self
action:@selector(showDetails)forControlEvents:UIControlEventTouchUpInside];
pinAnnotation.rightCalloutAccessoryView = infoButton;
}
else
{
pinAnnotation.image = [UIImage imageNamed:@"marker_red_postoffice.png"];
pinAnnotation.canShowCallout = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[infoButton addTarget:self action:@selector(showDetails)forControlEvents:UIControlEventTouchUpInside];
pinAnnotation.rightCalloutAccessoryView = infoButton;
}
}