Adding padding and border to an UIImageView
Asked Answered
N

2

16

How can I add padding between an UIImageView and its border?

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

Like this:

desired result

Neurophysiology answered 27/9, 2017 at 0:4 Comment(1)
Please check #20021978Rashad
R
26

As per the this link

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
    }
}
Rashad answered 27/9, 2017 at 0:48 Comment(2)
What is the "view" in view.addSubview(imageView) supposed to be? It's throwing me an error. Do I need to add a UIView to the image?Neurophysiology
Its just the view in ViewController.Rashad
R
0

For adding padding to the UIImage of UIImageView, use the below piece of code in Swift

let padding: CGFloat = 6    
myImageView.contentMode = .scaleAspectFill
myImageView.image = UIImage(named: "myImage.png").resizableImage(withCapInsets: UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding), resizingMode: .stretch)
Runkle answered 4/8, 2020 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.