Mapbox Аннотация Центрирование изображения

Я начал использовать MapBox в проекте. Когда я добавляю аннотацию с пользовательскими изображениями, она не центрируется правильно. Он выглядит немного ниже оригинальных контактов. Можно ли изменить центральную точку изображения аннотации?

Как это должно быть:

введите здесь описание изображения

Как обстоят дела сейчас:

введите здесь описание изображения

- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"driverPinId"];

    if (!annotationImage) {
        UIImage *image = [UIImage imageNamed:@"DriverPin"];
        annotationImageWithImage:image reuseIdentifier:@"driverPinId"];
    }

    return annotationImage;
}

person korgx9    schedule 23.05.2016    source источник
comment
@riedbunny можно ли сделать это без создания новых изображений с прозрачным нижним заполнением?   -  person korgx9    schedule 23.05.2016


Ответы (3)


Вы должны использовать MGLAnnotationView вместо MGLAnnotationImage, потому что MGLAnnotationView является потомком UIView, поэтому вы можете добавить к нему все, что хотите, как и в случае с обычным UIView.

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    guard annotation is MGLPointAnnotation else {
        return nil
    }
    guard let castAnnotation = annotation as? MapPointMarker else {
        return nil
    }
    if (!castAnnotation.willUseImage) {
        return nil;
    }

    let identifier = castAnnotation.imageName!
    var image: UIImage = UIImage(named: castAnnotation.imageName!)!

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

    if annotationView == nil {
        annotationView = MGLAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        let imageView = UIImageView(image: image)
        annotationView!.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
        annotationView?.addSubview(imageView)
        annotationView?.centerOffset = CGVector(dx: 0, dy: -image.size.height / 2.0)
    }

    return annotationView
}

Во фрагменте кода выше я добавляю UIImageView в annotationView и с помощью annotationView?.centerOffset = CGVector(dx: 0, dy: -image.size.height / 2.0) перемещаю изображение вверх.

Надеюсь, это поможет.

person Andrew Son    schedule 17.04.2018

Вам просто нужно настроить смещение центра MKAnnotationView в соответствии с размером вашего изображения.

Изменить: вы также можете проверить пример документа MapBox и описание здесь

Как говорится в документе:

- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation
{
    // Try to reuse the existing ‘pisa’ annotation image, if it exists
    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"pisa"];

    // If the ‘pisa’ annotation image hasn‘t been set yet, initialize it here
    if ( ! annotationImage)
    {
        // Leaning Tower of Pisa by Stefan Spieler from the Noun Project
        UIImage *image = [UIImage imageNamed:@"pisavector"];

        // The anchor point of an annotation is currently always the center. To
        // shift the anchor point to the bottom of the annotation, the image
        // asset includes transparent bottom padding equal to the original image
        // height.
        //
        // To make this padding non-interactive, we create another image object
        // with a custom alignment rect that excludes the padding.
        image = [image imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, image.size.height/2, 0)];

        // Initialize the ‘pisa’ annotation image with the UIImage we just loaded
        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"pisa"];
    }

    return annotationImage;
}
person MD.    schedule 23.05.2016
comment
Нет MKAnnotationView. Я использую MapBox. Это не ios mapkit по умолчанию - person korgx9; 23.05.2016
comment
@korgx9 позвольте мне проверить MapBox - person MD.; 23.05.2016
comment
Пока нет программного способа смещения центра, вам следует создать изображение с прозрачным отступом, которое вручную смещает ваш маркер. - person friedbunny; 23.05.2016
comment
Программное центрирование еще не реализовано? - person korgx9; 30.06.2016
comment
Представление аннотации будет сосредоточено в точке координат связанной аннотации. поэтому либо вам нужно изменить изображение, либо вы можете изменить смещение вида соответственно. - person MD.; 01.07.2016

Вам просто нужно настроить изображение, удвоив высоту изображения. Я проверил, и он работал отлично.

// Adjust image by doubling the height of the image
- (UIImage *)adjustImage:(UIImage *)image {

    CGSize newSize = CGSizeMake(image.size.width, image.size.height * 2);
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0);

    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:@"driverPinId"];

    if (!annotationImage) {
        UIImage *image = [UIImage imageNamed:@"DriverPin"];

        // The anchor point of an annotation is currently always the center. To
        // shift the anchor point to the bottom of the annotation, the image
        // asset includes transparent bottom padding equal to the original image
        // height.
        image = [self adjustImage: image];

        // To make this padding non-interactive, we create another image object
        // with a custom alignment rect that excludes the padding.
        image = [image imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, image.size.height/2, 0)];

        // Initialize the ‘DriverPin’ annotation image with the UIImage we just loaded.
        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:@"driverPinId"];
    }

    return annotationImage;
}
person Son Huynh    schedule 12.01.2017