Анимация импульсного кольца вокруг маркера Google Maps iOS

Я хочу добавить анимацию импульсного кольца вокруг маркера в качестве текущего местоположения пользователя на картах Google для iOS (например, Uber). Я попытался добавить CABasicAnimation к слою маркера с помощью addAnimation. Это не работает.

Также я попытался анимировать масштаб маркера, но изменения масштаба не произошло. Может ли кто-нибудь помочь мне с этим делом?


person Antony Raphel    schedule 16.12.2016    source источник
comment
Опубликуйте свой текущий код вместе с информацией о том, как он себя ведет. Не работает не очень информативно.   -  person Duncan C    schedule 16.12.2016
comment
@DuncanC код, который я обновил как ответ сейчас. Спасибо!   -  person Antony Raphel    schedule 16.12.2016


Ответы (1)


как-то сейчас работает. Я создал собственное представление и установил его в GMSMarker iconView. После этого добавил анимацию в слой просмотра.

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(200, 200, 100, 100)];
view.backgroundColor = [UIColor redColor];
view.layer.cornerRadius = 50;

GMSMarker *m = [GMSMarker markerWithPosition:mapView_.myLocation.coordinate];
m.iconView = view;
m.map = mapView_;


CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.duration = 1.5;
scaleAnimation.repeatCount = HUGE_VAL;
scaleAnimation.autoreverses = YES;
scaleAnimation.fromValue = [NSNumber numberWithFloat:0.1];
scaleAnimation.toValue = [NSNumber numberWithFloat:1.2];

[view.layer addAnimation:scaleAnimation forKey:@"scale"];

Другой метод:


GMSMarker *m = [GMSMarker markerWithPosition:mapView_.myLocation.coordinate];

//custom marker image
    UIImageView *pulseRingImg = [[UIImageView alloc] initWithFrame: CGRectMake(-30, -30, 78, 78)];
    pulseRingImg.image = [UIImage imageNamed:@"Pulse"];
    pulseRingImg.userInteractionEnabled = NO;


    //transform scale animation
    CABasicAnimation *theAnimation;
    theAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
    theAnimation.duration = 3.5;
    theAnimation.repeatCount = HUGE_VALF;
    theAnimation.autoreverses = NO;
    theAnimation.fromValue = [NSNumber numberWithFloat:0.0];
    theAnimation.toValue = [NSNumber numberWithFloat:2.0];

//alpha Animation for the image
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
    animation.duration = 3.5;
    animation.repeatCount = HUGE_VALF;
    animation.values = [NSArray arrayWithObjects:
                       [NSNumber numberWithFloat:1.0],
                       [NSNumber numberWithFloat:0.5],
                       [NSNumber numberWithFloat:0.0], nil];
    animation.keyTimes = [NSArray arrayWithObjects:
                         [NSNumber numberWithFloat:0.0],
                         [NSNumber numberWithFloat:1.2],
                         [NSNumber numberWithFloat:3.5], nil];
    [pulseRingImg.layer addAnimation:animation forKey:@"opacity"];


    [pulseRingImg.layer addAnimation:theAnimation forKey:@"pulse"];
    pulseRingImg.userInteractionEnabled = NO;

    m.iconView = pulseRingImg;
    [m.layer addSublayer:pulseRingImg.layer];
    m.map = mapView_;
    m.groundAnchor = CGPointMake(0.5, 0.5);

Еще один:

m = [GMSMarker markerWithPosition:mapView_.myLocation.coordinate];

    //custom marker image
    UIImageView *pulseRingImg = [[UIImageView alloc] initWithFrame: CGRectMake(-30, -30, 78, 78)];
    pulseRingImg.image = [UIImage imageNamed:@"Pulse"];
    pulseRingImg.userInteractionEnabled = NO;

    float duration = 3.5f;

    [CATransaction begin];
    [CATransaction setAnimationDuration: duration];

    //transform scale animation
    CABasicAnimation *theAnimation;
    theAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
    theAnimation.repeatCount = HUGE_VALF;
    theAnimation.autoreverses = NO;
    theAnimation.fromValue = [NSNumber numberWithFloat:0.0];
    theAnimation.toValue = [NSNumber numberWithFloat:2.0];

    [pulseRingImg.layer addAnimation:theAnimation forKey:@"pulse"];
    pulseRingImg.userInteractionEnabled = NO;

    [CATransaction setCompletionBlock:^{
        //alpha Animation for the image
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
        animation.duration = duration;
        animation.repeatCount = HUGE_VALF;
        animation.values = [NSArray arrayWithObjects:
                            [NSNumber numberWithFloat:1.0],
                            [NSNumber numberWithFloat:0.0], nil];
        [m.iconView.layer addAnimation:animation forKey:@"opacity"];
    }];

    [CATransaction commit];

    m.iconView = pulseRingImg;
    [m.layer addSublayer:pulseRingImg.layer];
    m.map = mapView_;
    m.groundAnchor = CGPointMake(0.5, 0.5);

Код Swift 3.0 ниже ПРИМЕЧАНИЕ. Измените продолжительность в соответствии с вашими требованиями.

           let m = GMSMarker(position: camera.target)

            //custom marker image
            let pulseRingImg = UIImageView(frame: CGRect(x: -30, y: -30, width: 78, height: 78))
            pulseRingImg.image = UIImage(named: "Pulse")
            pulseRingImg.isUserInteractionEnabled = false
            CATransaction.begin()
            CATransaction.setAnimationDuration(3.5)

            //transform scale animation
            var theAnimation: CABasicAnimation?
            theAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
            theAnimation?.repeatCount = Float.infinity
            theAnimation?.autoreverses = false
            theAnimation?.fromValue = Float(0.0)
            theAnimation?.toValue = Float(2.0)
            theAnimation?.isRemovedOnCompletion = false

            pulseRingImg.layer.add(theAnimation!, forKey: "pulse")
            pulseRingImg.isUserInteractionEnabled = false
            CATransaction.setCompletionBlock({() -> Void in

                //alpha Animation for the image
                let animation = CAKeyframeAnimation(keyPath: "opacity")
                animation.duration = 3.5
                animation.repeatCount = Float.infinity
                animation.values = [Float(2.0), Float(0.0)]
                m.iconView?.layer.add(animation, forKey: "opacity")
            })

            CATransaction.commit()
            m.iconView = pulseRingImg
            m.layer.addSublayer(pulseRingImg.layer)
            m.map = gmapView
            m.groundAnchor = CGPoint(x: 0.5, y: 0.5)

изображение пульса: импульсное изображение для анимации

person Antony Raphel    schedule 16.12.2016
comment
Я рад, что вы нашли решение. Чтобы сделать ваш код более модульным, вы можете подумать о том, чтобы сделать пульсирующее представление пользовательским подклассом GMSMarker. Это сделало бы его более удобным и многоразовым. (И вы должны принять свой ответ, как только система позволит вам это сделать.) - person Duncan C; 16.12.2016
comment
@Duncan C, спасибо! Да, я должен реализовать таким образом, как многоразовый. Если вы можете помочь мне с образцом кода, это в основном приветствуется. - person Antony Raphel; 17.12.2016
comment
@bsm-2000 Код Swift 3.0 обновлен в ответе. Взгляните на это! - person Antony Raphel; 24.08.2017
comment
@AntonyRaphel Вау, все работает отлично, большое спасибо - person bsm-2000; 24.08.2017
comment
В вашем ответе опечатка. Для имени изображения вы написали pluse во втором методе. Но во всех других местах вашего кода вы использовали Pulse. Пожалуйста, сделайте его похожим. Кстати, ваш ответ был полезен. Спасибо - person Zohaib Hassan; 05.12.2017
comment
Проблема @Antony Raphel возникает при установке анимации [CABasicAnimation animationWithKeyPath: @transform.scale] в представлении значка, поэтому представление будет вибрировать (дрожать) - person Yogendra Patel; 11.04.2018
comment
после использования этой анимации CPU LOAD 96%. - person Harshil Kotecha; 09.05.2018
comment
@Harshil, ты использовал это на Картах Google? - person Antony Raphel; 09.05.2018
comment
@AntonyRafel Да - person Harshil Kotecha; 09.05.2018
comment
@Harshil это из-за загрузки Google Maps. Не из-за этого кода. Спасибо! - person Antony Raphel; 09.05.2018
comment
@AntonyRaphel хорошо, спасибо, у меня есть проверка без карты и с картой, и этот процессор загружается не из-за анимации - person Harshil Kotecha; 09.05.2018
comment
Большое спасибо. Такое отличное решение. - person BharathRao; 13.12.2019