I want to shake the google map marker in iOS Swift

前端 未结 2 640
小鲜肉
小鲜肉 2021-01-15 16:46

I am working on a project where I wants to shake the marker on google Map. I am using the custom marker icon to represent on the map. Like a head of person is shaking. I don

2条回答
  •  臣服心动
    2021-01-15 17:13

    You can add a CAKeyframeAnimation or CABasicAnimation to your marker.iconView!.layer we add a UIView with a frame bigger than our UIImageView inside then we need to adjust the anchor point of your UIImageView to bottom in vertical and horizontally centered this will be the point that will work as pivot in our animation, our animation will be a rotation animation in Z plane from -30 to 30 grades to achieve the animation desired.This is the simplest way to do this but you can also define a custom class and make a lot of other things

        let marker = GMSMarker(position: CLLocationCoordinate2D(latitude: 22.404963, longitude: -79.961755))
    
        //we need a bigger UIView to avoid the clip problem with the UIImageView
        marker.iconView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 40))
        let imageView = UIImageView(frame: CGRect(x: (marker.iconView?.frame.width)!/2 - 14, y: (marker.iconView?.frame.height)! - 36, width: 28, height: 36))
        imageView.contentMode = .scaleAspectFit
        imageView.image = UIImage(named: "iconomapa")
        marker.iconView?.addSubview(imageView)
        imageView.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0) //we need adjust anchor point to achieve the desired behavior
        imageView.layer.frame = CGRect(x: (marker.iconView?.frame.width)!/2 - 14, y: (marker.iconView?.frame.height)! - 36, width: 28, height: 36) //we need adjust the layer frame
    
        let animation = CAKeyframeAnimation()
        animation.keyPath = "transform.rotation.z"
        animation.values = [ 0, -30 * .pi / 180.0, 30 * .pi / 180.0 , 0]
        animation.keyTimes = [0, 0.33 , 0.66 , 1]
        animation.duration = 1;
        animation.isAdditive = false;
        animation.isRemovedOnCompletion = true
        animation.repeatCount = .infinity
    
        marker.iconView!.subviews[0].layer.add(animation, forKey: "shakeAnimation")
        marker.map = self.mapView
    

    here is how it looks

    Hope this helps

提交回复
热议问题