How to create rounded image with border and shadow

2019-07-16 13:45发布

问题:

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.