Swift - setting rounded corners to annotation view image

房东的猫 提交于 2019-12-04 13:39:37

I found the solution for this and is it quite elegant I think.

Rather than changing the layer of the annotation, create a UIImageView, attach an image to it and add it as view to the annoation.

    let imageView = UIImageView(frame: CGRectMake(0, 0, 25, 25))
    imageView.image = UIImage(named: cpa.imageName);
    imageView.layer.cornerRadius = imageView.layer.frame.size.width / 2
    imageView.layer.masksToBounds = true
    anView.addSubview(imageView)

Let me know if does work for you.

DZ

Just to add to dizzie's great answer:

Adding the image subview works well, but the pin can no longer be clicked. I found that changing the pin's size to match the image's solves this issue.

anView.frame = imageView.frame

You might also want to move the callout, depending on the size of your image.

anView.calloutOffseet = CGPoint(x: 0, y: -10)

Another approach is adding a sublayer instead a imageView like so:

let imageLayer = CALayer()
imageLayer.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
imageLayer.contents = image?.cgImage
imageLayer.cornerRadius = imageLayer.frame.size.width / 2
imageLayer.masksToBounds = true
imageLayer.borderWidth = 4.0
imageLayer.borderColor = UIColor.white.cgColor
anView.layer.addSublayer(imageLayer)
anView.frame = imageLayer.frame
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!