Проблема изменения размера изображения пин-кода MKAnontation - PullRequest
0 голосов
/ 08 января 2019

Пин-код для MKAnnotation. При касании или увеличении карты пользовательский штифт растягивается, и отверстие для маркера автомобиля на домашней карте большого размера. Вот результат вывода, который я получаю в mapview:

enter image description here

Вот код, который я пробовал до сих пор:

var pin = MKAnnotationView()
var userPinView: MKAnnotationView!

if annotation is MKUserLocation {

    pin = mapView.view(for: annotation) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
    let pinImage = UIImage(named: "carIcon3")
    let size = CGSize(width: 38, height: 44)
    UIGraphicsBeginImageContext(size)
    pinImage!.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    pin.image = resizedImag
    userPinView = pin
    userPinView.contentMode = .scaleAspectFill
    userPinView.clipsToBounds = true
    return pin
}

if !(annotation is MKPointAnnotation) {
    return nil
}

let annotationIdentifier = "AnnotationIdentifier"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

if annotationView == nil {
    annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
    //            annotationView!.canShowCallout = true
} else {
    annotationView!.annotation = annotation
}
return annotationView

Как получить такой результат:

enter image description here

Попытка пользователя маркер текущего местоположения. Но это сбой

   func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {

        UIView.animate(withDuration: 0.005) {

        let angle = newHeading.trueHeading.toRadians() // convert from degrees to radians

        self.userPinView.transform = CGAffineTransform(rotationAngle: CGFloat(angle)) // rotate the picture
    }
}

здесь код, который я выполнил didselect и снимите выделение для аннотации местоположения.

     func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    if annotView == true {

        let heights = 70

        let widths = 50

        UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveLinear, animations: {

            view.frame.size = CGSize(width: widths, height: heights)

        })
    }

}

func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {

    let heights = 70

    let widths = 50

    UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveLinear, animations: {

        view.frame.size = CGSize(width: view.frame.width - CGFloat(widths), height: view.frame.height - CGFloat(heights))

    })
}

1 Ответ

0 голосов
/ 09 января 2019

Хотя я не могу воспроизвести проблему, но рекомендую несколько изменений:

  1. разделяет логику конфигурации представления, позволяет подклассу MKAnnotationView, вот так:

    class CarAnnotationView: MKAnnotationView {
        override var annotation: MKAnnotation? {
            didSet {
                let size = CGSize(width: 38, height: 44)
                UIGraphicsBeginImageContext(size)
                UIImage(named: "carIcon")?.draw(in: CGRect(origin: .zero, size: size))
                self.image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
            }
        }
    }
    
  2. изменить в mapView(_:viewFor:), чтобы воспользоваться преимуществами многоразового просмотра, например:

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            userPinView = mapView.dequeueReusableAnnotationView(withIdentifier: "carId") as? CarAnnotationView
            if (userPinView == nil) {
                userPinView = CarAnnotationView(annotation: nil, reuseIdentifier: "carId")
            }
    
            userPinView.annotation = annotation
            userPinView.setNeedsLayout()
            // userPinView.centerOffset = CGPoint(x: 0, y: -view.bounds.midY)
    
            return userPinView
        }
    
        guard annotation is MKPointAnnotation else { return nil }
    
        let annotationIdentifier = "AnnotationIdentifier"
        ...
        return annotationView
    
    }
    
  3. удалить ненужную переменную

    var pin = MKAnnotationView()
    
...