How to create rounded image with border and shadow as MKAnnotationView in Swift?

 ̄綄美尐妖づ 提交于 2019-12-14 03:54:00

问题


I'd like to create MKAnnotationView that looks like the one below.

The code I already have:

func maskRoundedImage(image: UIImage, radius: Float) -> UIImage {
    let imageView: UIImageView = UIImageView(image: image)
    var layer: CALayer = CALayer()
    layer = imageView.layer

    layer.masksToBounds = true
    layer.cornerRadius = CGFloat(radius)
    layer.borderWidth = 4.0
    layer.borderColor = UIColor.whiteColor().CGColor

    UIGraphicsBeginImageContext(imageView.bounds.size)
    layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return roundedImage
}

func imageResize (image:UIImage, sizeChange:CGSize)-> UIImage{

    let hasAlpha = true
    let scale: CGFloat = 0.0 // Use scale factor of main screen

    UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
    image.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))

    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    return scaledImage
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationReuseId = "Place"
    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId)
    if anView == nil {
        anView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId)
    } else {
        anView!.annotation = annotation
    }

    let imageString = User.UserData.base64String
    let image = convertBase64ToImage(imageString!)
    let size = CGSizeMake(40, 40)

    let resizedImage = imageResize(image, sizeChange: size)
    anView?.image = maskRoundedImage(resizedImage, radius: 20)

    anView!.backgroundColor = UIColor.clearColor()
    anView!.canShowCallout = true
    return anView
}

The thing is my image is very poor quality. Do you have any ideas what I can do to improve the quality and how to add the shadow?


回答1:


before returning your new "anView" you can use this code:

anView!.layer.cornerRadius = anView!.frame.size.height/2
anView!.layer.masksToBounds = true
anView!.layer.borderColor = UIColor.whiteColor()
anView!.layer.borderWidth = 5

That'll make it round with a white border.

If instead you want a border on the image itself you could just use an Image View and put it as a subview of your MKAnnotationView.



来源:https://stackoverflow.com/questions/37270970/how-to-create-rounded-image-with-border-and-shadow-as-mkannotationview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!