web-dev-qa-db-fra.com

Ajout d'un remplissage et d'une bordure à une UIImageView

Comment puis-je ajouter un remplissage entre une UIImageView et sa bordure?

    Img.layer.cornerRadius = Img.bounds.width / 2
    Img.layer.borderWidth = 2
    Img.layer.borderColor = UIColor.blue.cgColor
    Img.clipsToBounds = true

Comme ça:

enter image description here

10
ILoveToCode22

Selon le ce lien

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "imagename")!
        let imageView = UIImageView(image: image.imageWithInsets(insets: UIEdgeInsetsMake(30, 30, 30, 30)))
        imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
        imageView.backgroundColor = UIColor.gray
        imageView.layer.borderWidth = 2
        imageView.layer.borderColor = UIColor.blue.cgColor
        view.addSubview(imageView)
    }
}
extension UIImage {
    func imageWithInsets(insets: UIEdgeInsets) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(
            CGSize(width: self.size.width + insets.left + insets.right,
                   height: self.size.height + insets.top + insets.bottom), false, self.scale)
        let _ = UIGraphicsGetCurrentContext()
        let Origin = CGPoint(x: insets.left, y: insets.top)
        self.draw(at: Origin)
        let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return imageWithInsets
    }
}
12
Vini App