Подтвердить что ты не робот

MKPinAnnotationView: Доступно ли более трех цветов?

В соответствии с документами Apple цвет контактов MKPinAnnotationView доступен в красном, зеленом и фиолетовом цветах. Есть ли способ получить другие цвета? Я ничего не нашел в документах.

4b9b3361

Ответ 1

Возможно, вам понадобятся следующие изображения:

alt textalt textalt textalt text

и код для использования в viewForAnnotation:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{   
    // ... get the annotation delegate and allocate the MKAnnotationView (annView)
    if ([annotationDelegate.type localizedCaseInsensitiveCompare:@"NeedsBluePin"] == NSOrderedSame)
    {
        UIImage * image = [UIImage imageNamed:@"blue_pin.png"];
        UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
        [annView addSubview:imageView];
    }
    // ...

Ответ 2

еще несколько;)

alt text http://lionel.gueganton.free.fr/pins/pinGray.png enter image description hereenter image description here

alt text http://lionel.gueganton.free.fr/pins/pinOrange.png enter image description hereenter image description here

И оригинальные:

alt text http://lionel.gueganton.free.fr/pins/pinGreen.png alt textenter image description here

alt text http://lionel.gueganton.free.fr/pins/pinPurple.png alt textenter image description here

alt text http://lionel.gueganton.free.fr/pins/pinRed.png alt textenter image description here

И код:

- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
MKPinAnnotationView* anView =[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"test"];
anView.pinColor=MKPinAnnotationColorPurple;
UIImage* image = nil;
// 2.0 is for retina. Use 3.0 for iPhone6+, 1.0 for "classic" res.
UIGraphicsBeginImageContextWithOptions(anView.frame.size, NO, 2.0);
[anView.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData* imgData = UIImagePNGRepresentation(image);
NSString* targetPath = [NSString stringWithFormat:@"%@/%@", [self writablePath], @"thisismypin.png" ];
[imgData writeToFile:targetPath atomically:YES]; 
return anView;
}

-(NSString*) writablePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}

Ответ 3

Вы можете использовать ZSPinAnnotation для создания клипов аннотации "на лету" с указанным UIColor: https://github.com/nnhubbard/ZSPinAnnotation

Ответ 4

Мне нравится Yonel Answer, но только хэдз-ап, когда вы создаете пользовательский MKAnnotationView, вам придется вручную назначить смещение. Для изображений, предоставленных Yonel: (вы можете оставить содержимое calloutButton, если вам не нужен один из них)

#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if(![annotation isKindOfClass:[MyAnnotation class]]) // Don't mess user location
        return nil;

    MKAnnotationView *annotationView = [aMapView dequeueReusableAnnotationViewWithIdentifier:@"spot"];
    if(!annotationView)
    {
        annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"spot"];
        annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [(UIButton *)annotationView.rightCalloutAccessoryView addTarget:self action:@selector(openSpot:) forControlEvents:UIControlEventTouchUpInside];
        annotationView.enabled = YES;
        annotationView.canShowCallout = YES;
        annotationView.centerOffset = CGPointMake(7,-15);
        annotationView.calloutOffset = CGPointMake(-8,0);
    }

    // Setup annotation view
    annotationView.image = [UIImage imageNamed:@"pinYellow.png"]; // Or whatever

    return annotationView;
}

Ответ 6

С iOS 9, pinTintColor добавлен в MKPinAnnotationView, что позволяет вам указать UIColor для цвета контактов.

Ответ 7

Ни один из опубликованных решений не работает на 100%, если вы используете анимацию drop drop. Решение Cannonade очень аккуратно, потому что оно позволяет штифту иметь оба конца (острая точка при падении и одна с круговой бумажной пульсацией), но, к сожалению, проблеск первоначального цвета головки колодки можно увидеть, когда штырь отскакивает, как он попадает на карту. yonel решение замены всего изображения штифта означает, что штифт падает с круговой бумажной пульсацией, прежде чем он даже попадет на карту!

Ответ 8

Я пробовал этот путь, и кажется, все в порядке...

UIImage * image = [UIImage imageNamed:@"blue_pin.png"];
        UIImageView *imageView = [[[UIImageView alloc] initWithImage:image]
                                 autorelease];
        [annotationView addSubview:imageView];
        annotationView = nil;

с использованием полного пин-изображения... в качестве примера yonel

Ответ 9

Если это не в документах, то, скорее всего, нет, вы cAn используете mkannotationview и имеете собственное изображение ur, если хотите, но