Rounding UIImage and adding a border

前端 未结 9 1148
青春惊慌失措
青春惊慌失措 2020-12-09 18:19

so I want to show some pictures as annotations on the map. In order to do that I need to add the image property of the MKAnnotationView. I\'m using the regular images but I

9条回答
  •  失恋的感觉
    2020-12-09 18:31

    Leo Dabus's solution in Swift 3:

    extension UIImage {
        func roundedImageWithBorder(width: CGFloat, color: UIColor) -> UIImage? {
            let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
            let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
            imageView.contentMode = .center
            imageView.image = self
            imageView.layer.cornerRadius = square.width/2
            imageView.layer.masksToBounds = true
            imageView.layer.borderWidth = width
            imageView.layer.borderColor = color.cgColor
            UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
            guard let context = UIGraphicsGetCurrentContext() else { return nil }
            imageView.layer.render(in: context)
            let result = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return result
        }
    }
    

提交回复
热议问题