В соответствии с документами Apple цвет контактов MKPinAnnotationView доступен в красном, зеленом и фиолетовом цветах. Есть ли способ получить другие цвета? Я ничего не нашел в документах.
MKPinAnnotationView: Доступно ли более трех цветов?
Ответ 1
Возможно, вам понадобятся следующие изображения:
и код для использования в 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
alt text http://lionel.gueganton.free.fr/pins/pinOrange.png
И оригинальные:
alt text http://lionel.gueganton.free.fr/pins/pinGreen.png
alt text http://lionel.gueganton.free.fr/pins/pinPurple.png
alt text http://lionel.gueganton.free.fr/pins/pinRed.png
И код:
- (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;
}
Ответ 5
И вот PSD для штыря с тенью и его размером @2x.
http://dl.dropbox.com/u/5622711/ios-pin.psd
Используйте этот PSD для любого цвета, который вы хотите:)
Я не отношусь к этому PSD. Я просто схватил его от http://www.teehanlax.com/downloads/iphone-4-guid-psd-retina-display/ Они проделали замечательную работу!
Ответ 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, если хотите, но