MKAnnotationView 图像切换的过渡问题

MKAnnotationView image toggling's transition issue

我有 2 个 MKAnnotationView 图像状态,它们是 selecteddeselected。问题是这两种状态之间的转换很差。网上没有太多关于这方面的内容,而且我在转换时遇到了问题,一般来说。

这是我正在使用的MKAnnotationView

class CustomPinView: MKAnnotationView {
    func updateImage() {
        guard let mapAnnotation = annotation as? MapAnnotation else {return}
        if let selectedImageName = mapAnnotation.selectedImageName, isSelected {
            image = UIImage(inCurrentBundleWithName: selectedImageName)
        } else if let imageName = mapAnnotation.imageName {
            image = UIImage(inCurrentBundleWithName: imageName)
        } else {
            image = nil
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        updateImage()
    }

    override var annotation: MKAnnotation? {
        didSet {
            updateImage()
        }
  }
}

我将 updateImage 函数更新为如下所示:

private func updateImage() {
        CATransaction.begin()
        CATransaction.setAnimationDuration(0.2)
        CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .easeOut))
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
            guard let mapAnnotation = self.annotation as? MapAnnotation else {return}
            if let selectedImageName = mapAnnotation.selectedImageName, self.isSelected {
                self.image = UIImage(inCurrentBundleWithName: selectedImageName)
                self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.6)
            } else if let imageName = mapAnnotation.imageName {
                self.image = UIImage(inCurrentBundleWithName: imageName)
                self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            } else {
                self.image = nil
            }
            self.centerOffset = CGPoint(x: 0.5, y: 0.5)
        }, completion: nil)
        CATransaction.commit()
    }

这是从这里的答案中提取的: