如何使用动态元素创建自定义地图视图图钉?

时间:2017-03-24 21:22:41

标签: ios swift mkmapview

我正在尝试创建一个自定义引脚,在引脚的中心有一个标签,它会随每个引脚而变化。标签只是引脚号,所以如果我有8个引脚,每个引脚将在中心有一个数字,即第一个引脚将有1个,第二个引脚将有2个,等等。问题是常规引脚出现,而不是定制别针。

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    loadPins()
}

func loadPins() {
        let annotation = CustomPin()
        annotation.coordinate = CLLocationCoordinate2D(latitude: 30.2531419, longitude: -97.78785789999999)
        mapView.addAnnotation(annotation)
    }


class AnView: UIView {


    @IBOutlet weak var countLabel: UILabel!
    @IBOutlet weak var pinImage: UIImageView!


    override func draw(_ rect: CGRect) {
        //Draw function
    }

}

class CustomPin: MKPointAnnotation {
    var pin = AnView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

}

2 个答案:

答案 0 :(得分:0)

注释(您的CustomPin)获取纬度/经度值。

注释视图(您的代码未显示)获取您要在地图上显示的标签或图像。

由于评论中的Maps and Location Programming Guide提供了Objective-C中的所有示例,因此您可能还需要查看此RayWenderlich.com教程以获取Swift帮助: MapKit Tutorial: Getting Started

答案 1 :(得分:0)

您可以在地图图钉图像上绘制数字。只需创建一个函数(或扩展名)即可在图像上添加文字,如下所示:

func addTextOverImage(_ text: String, overImage image: UIImage) -> UIImage {

    //set scale and context
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

    //set font face, size and color
    let textColor = UIColor.black
    let textFont = UIFont.boldSystemFont(ofSize: 12)

    //define the text attributes
    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center

    let textFontAttributes = [
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: textColor,
        NSParagraphStyleAttributeName: paragraph
        ] as [String : Any]

    //set the text position (in the image rect)
    let textPoint=CGPoint.init(x: 0.0, y: image.size.height/2)
    //create the rect to draw the text
    let rect = CGRect(origin: textPoint, size: image.size)
    //draw the text over the image, in the rect just defined
    text.draw(in: rect, withAttributes: textFontAttributes)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //return image with text
    return newImage!
}

您可能需要调整函数中的textPoint以使文本位于您希望的位置。