Swift - 将圆角设置为注释视图图像

时间:2015-01-20 12:48:42

标签: ios swift mapkit mkannotation mkannotationview

这是我之前的帖子,我将图像设置为注释视图引脚

Swift - setting different images from array to annotation pins

现在我遇到了在注释视图图像上设置圆角的问题。

cannot show callout with clipsToBounds enabled swift

似乎我必须在圆角或显示标注之间做出选择,我真的不明白为什么这两个不能出现。有没有办法做到这一点? 这是我的viewForAnnotation函数:

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if !(annotation is RestaurantAnnotation) {
        return nil
    }

    let reuseId = "restaurant"
    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    if anView == nil {
        anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        anView.canShowCallout = false
    }
    else {
        anView.annotation = annotation

    }

    let restaurantAnnotation = annotation as RestaurantAnnotation

    if (restaurantAnnotation.image != nil) {

                        anView.image = restaurantAnnotation.image!

                        anView.layer.masksToBounds = true

                        anView.layer.cornerRadius = (anView.frame.size.height)/10.0

    }
    else {
        // Perhaps set some default image
    }

    return anView
}

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:14)

我找到了解决方案,我觉得这很优雅。

不是更改注释的图层,而是创建一个UIImageView,将图像附加到它上面并将其作为视图添加到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)

让我知道是否适合你。

DZ

答案 1 :(得分:3)

只是为了加入dizzie的好答案:

添加图像子视图效果很好,但无法再单击该图钉。 我发现更改引脚的大小以匹配图像可以解决这个问题。

anView.frame = imageView.frame

您可能还想移动标注,具体取决于图片的大小。

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

答案 2 :(得分:0)

另一种方法是添加一个子层,而不是像这样的imageView:

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
相关问题