1

I'm trying to draw a marker on an image (MKSnapshot) with a title, but the title is not showing up.
Does anyone has any idea why this would be the case?

let annotation = MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = "TitleTest"
let pinView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "test")
    pinView.titleVisibility = MKFeatureVisibility.visible
    pinView.dragState = .none
    pinView.animatesWhenAdded = false
    pinView.canShowCallout = false
    pinView.titleVisibility = .visible
    pinView.contentMode = .scaleAspectFit
    pinView.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
    if rect!.contains(point) {
        let pinCenterOffset = pinView.centerOffset
        point.x -= pinView.bounds.size.width / 2
        point.y -= pinView.bounds.size.height / 2
        point.x += pinCenterOffset.x
        point.y += pinCenterOffset.y
    }
    pinView.drawHierarchy(in: CGRect(
            x:point.x,
            y:point.y,
            width:pinView.bounds.width,
            height:pinView.bounds.height),
        afterScreenUpdates: true)
    print("Draw a marker on iOS 11")

This is a screenshot of my UIImageView with the marker, but without the title:

Screenshot of my UIImageView with marker but without title

zx485
  • 28,498
  • 28
  • 50
  • 59

1 Answers1

0

The title can be drawn on the snapshot below the location of the pin:

  • determine the position of the annotation in the coordinate system of the image snapshot.point(for: annotation.coordinate)

  • create the attributes for title text, you can make it similar to what Apple uses:

    private func titleAttributes() -> [NSAttributedStringKey: NSObject] {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
        let titleFont = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.semibold)
        let attrs = [NSAttributedStringKey.font: titleFont,
                     NSAttributedStringKey.paragraphStyle: paragraphStyle]
        return attrs
    }
    
  • draw it right below the position of the annotation:

    private func drawTitle(title: String,
                           at point: CGPoint,
                           attributes: [NSAttributedStringKey: NSObject]) {
        let titleSize = title.size(withAttributes: attributes)
        title.draw(with: CGRect(
            x: point.x - titleSize.width / 2.0,
            y: point.y + 1,
            width: titleSize.width,
            height: titleSize.height),
                   options: .usesLineFragmentOrigin,
                   attributes: attributes,
                   context: nil)
    }
    

For a more complete example with code and a screenshot, see my following answer (it draws a custom pin image but the rest of the code can be used here).

Stephan Schlecht
  • 26,556
  • 1
  • 33
  • 47