Загруженное изображение MKPinAnnotationView (@ 3x) не работает для 6+

Я использую карту в своем приложении. Для сброса булавки я хочу установить изображение пользователя вместо булавки по умолчанию.

Я загружаю изображение пользователя и устанавливаю его в соответствии с кодом, который я вставляю ниже.

Для разных масштабов устройств я использую имя изображения в соответствии с масштабом устройства, например,

1 Для устройств без сетчатки - pin.png (размер 30 x 30)

2 Для устройств Retina - [email protected] (размер 60 x 60)

3 Для устройств 6+ - [email protected] (размер 90 x 90)

Здесь для 1 и 2 работают нормально, и изображение загружается идеально, но для 6+ (3-кратный масштаб) он не работает

В чем проблема:

Для 6+ я загружаю изображение pin @ 3x, но на карте его размер составляет 90 x 90, что должно быть 30 x 30. Поскольку это просто работает для изображений, когда мы используем из пакета приложений.

Для [email protected] он отлично работает и показывает 2-кратное изображение размером 30 x 30.

Я также попробовал решение ниже, установив масштаб изображения, но не работает

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

Я изо всех сил старался объяснить реальную проблему. Может ли какое-нибудь руководство, пожалуйста, если мне что-то не хватает или требуется что-то установить?

Код

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

MKPinAnnotationView *annotationView = nil;

if ([annotation isKindOfClass:[MKUserLocation class]])
{
    return nil;
}

if ([annotation isKindOfClass:[KPAnnotation class]])
{
    //Custom annotation class for pin drop
    KPAnnotation *a = (KPAnnotation *)annotation;

    annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"pin"];

    if (annotationView == nil)
    {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:[a.annotations anyObject]
                                                         reuseIdentifier:@"pin"];
    }

    //Image View to add subview in MKPinAnnotationView
    UIImageView *imageView = [[UIImageView alloc] init];
    UIImage * image = [UIImage imageNamed:@"pin.png"];
    imageView.image=image;

    //Test URL - see image name here
    NSString *readAWSURL=@"<domainname.com>/[email protected]";

    //Downloading image here to load with async way (SDWebImage)
    [imageView sd_setImageWithURL:[NSURL URLWithString:readAWSURL] placeholderImage:[UIImage imageNamed:@"pin.png"]];

    annotationView.image=imageView.image;
    [annotationView addSubview:imageView];
    annotationView.canShowCallout = YES;
}

return annotationView;

}

person Niks    schedule 27.05.2015    source источник


Ответы (2)


Используйте MKAnnotationView вместо MKPinAnnotationView.

- (MKAnnotationView ) mapView: (MKMapView ) mapViewIn viewForAnnotation:(id<MKAnnotation>) annotation
{

static NSString *annotationViewReuseIdentifier = @"annotationViewReuseIdentifier";

MKAnnotationView annotationView = (MKAnnotationView )[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier];

if (annotationView == nil)
{
    annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier];
}

if ([annotation isKindOfClass:[MapPoint class]]) {
    annotationView.image = [UIImage imageNamed:@"orange.png"];
    annotationView.canShowCallout = NO;
}
else{
    annotationView.image = [UIImage imageNamed:@"blue.png"];
    annotationView.canShowCallout = YES;
}

annotationView.annotation = annotation;
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
return annotationView;
}
person Developer    schedule 02.11.2015
comment
ну, у меня была проблема с загрузкой изображения и отображением на карте. Не было проблем с отображением изображения из пакета. Чтобы показать из комплекта, он работает нормально. - person Niks; 04.11.2015

Мой ответ сейчас работает для меня. Он основан на _1 _, _ 2_ и бородатом ответе от @mokriya http://mokriya.tumblr.com/post/15342072745/dynamic-annotations-mkannotationview-for-ios Просто добавьте категорию MKAnnotationView (WebCache):

#import <MapKit/MapKit.h>

@interface MKAnnotationView(WebCache)

- (void)setImageWithUrl:(NSURL *)url;

@end

и реализация (не идеальная, но работающая):

#import "MKAnnotationView+WebCache.h"
#import "UIImageView+WebCache.h"
#import "UIImage+Resize.h"

#define kIconSize CGSizeMake(50, 50)

@implementation MKAnnotationView(WebCache)

- (void)setImageWithUrl:(NSURL *)url {
    [[[UIImageView alloc] init] sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.image = [image resizedImageToSize:kIconSize];
    }];
}

@end

и используя:

#pragma mark - MKMapViewDelegate

- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    static NSString *annotationViewReuseIdentifier = @"annotationViewReuseIdentifier";

    MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier];

    if (!annotationView) {
        annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier];
        annotationView.canShowCallout = YES;
    }

    annotationView.annotation = <YOUR ANNOTATION>;
    [annotationView setImageWithUrl:<HERE IS THE URL>];

    return annotationView;
}
person WINSergey    schedule 09.04.2017