Padding around UIImageView. Swift 3

Viewed 20065

I have a UIImageView, where I don't want the image to 'touch' the edge of the view, rather have some 'padding' around it. However, I have tried the following, and for some reason it doesnt change:

@IBOutlet weak var pictureOutletOne: UIImageView!

//set the image
pictureOutletOne.image = UIImage(named: itemOne)

//set the padding
pictureOutletOne.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10);

I have also tried:

pictureOutletOne.translatesAutoresizingMaskIntoConstraints = false
pictureOutletOne.layoutMargins = UIEdgeInsets(top: 10, left: 100, bottom: 10, right: 0)

I have read alot about this, but these are the solutions I have found, but they aren't working. Using Swift 3.

Thanks so much.

6 Answers

Swift 4.2 & 5

let imageView = UIImageView()
imageView.image = UIImage(named: 
"image")?.withAlignmentRectInsets(UIEdgeInsets(top: -5, left: -5, bottom: -5, 
right: -5))

Insets should be given in negative value

Override the alignmentRectInsets property in a new class:

class PaddedImageView: UIImageView {
    override var alignmentRectInsets: UIEdgeInsets {
        return UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
    }
}

Swift 5.4 & Xcode 13

Here is a little helper extension I build:

extension UIImage {
    func addPadding(_ padding: CGFloat) -> UIImage {
        let alignmentInset = UIEdgeInsets(top: -padding, left: -padding,
                                          bottom: -padding, right: -padding)
        return withAlignmentRectInsets(alignmentInset)
    }
}
let padding: CGFloat = 10    
myImageView.contentMode = .scaleAspectFill
myImageView.image = UIImage(named: "myImage.png").resizableImage(withCapInsets: UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding), resizingMode: .stretch)

Swift 5

Adds padding to right and left of an image place in an image view.

        let image = UIImage(systemName: "circle.fill")
        let insets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: -15)
        let imageView = UIImageView(image: image.withAlignmentRectInsets(insets))
Note: UIStackView honors alignment insets as contributors to an image view's intrinsic content size.

Use case example:

In my application, I have a vertical stack comprised of a small center-aligned UILabel stacked above a UIImageView in a UITableViewCell. Label width varies from cell to cell, varying respective vertical stack widths and shifting images' respective horizontal alignments. I.e. the images don't line up in the table.... By padding images with horizontal alignment insets, it forces vertical stack to have a consistent width greater than max expected label width, keeping images center-aligned vertically in the table.

Related