UIImageView周围的填充。Swift 3

21

我有一个UIImageView,我不想让图像“触碰”视图的边缘,而是希望在它周围有一些“填充”。但是,我已经尝试了以下操作,但出于某种原因它没有改变:

@IBOutlet weak var pictureOutletOne: UIImageView!

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

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

我也尝试过:

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

我已经阅读了很多关于这个的内容,但这些是我找到的解决方案,但它们并没有起作用。使用Swift 3

非常感谢。


1
layoutMargins only affect subviews that use them. UIImageView renders image inside in a non-UIView way so you should follow with the answer below where you wrap it into UIView - pronebird
请访问https://dev59.com/O1YO5IYBdhLWcg3wDNbI。 - Saeed Alizadeh
6个回答

27

Swift 4.2 & 5

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

内边距应该给负值。


4
不幸的是,这种方法无法处理带有圆角边框的图像视图。 - geoff

9
您可以将imageView插入到视图中,并设置约束来保证其对齐两侧。这是一种可靠的方法 :)

Dominik。你好。我是一个初学者,你能告诉我如何将imageView放入一个view中吗? - RJB
2
您可以选择imageView并转到菜单,Editor> Embed In> View。这样做,您的imageView将分配到一个新创建的视图中。但不要忘记重新应用约束。 - dede.exe
这仅适用于您假设该人正在使用nib或storyboard。这在代码中无法帮助。 - TJ Olsen
@TJOlsen 你可以在代码中使用NSLayoutConstraint和UIView来应用相同的方法。 - undefined

6

在一个新的类中覆盖alignmentRectInsets属性:

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

3

这是我编写的一个小助手扩展:

extension UIImage {
    func addPadding(_ padding: CGFloat) -> UIImage {
        let alignmentInset = UIEdgeInsets(top: -padding, left: -padding,
                                          bottom: -padding, right: -padding)
        return withAlignmentRectInsets(alignmentInset)
    }
}

你必须提供一个使用示例,而不仅仅展示功能...白痴。 - undefined

0

Swift 5

在图像视图中放置一个图片,可以在左右两侧添加填充。

let image = UIImage(systemName: "circle.fill")
let insets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: -15)
let imageView = UIImageView(image: image.withAlignmentRectInsets(insets))

注意:UIStackView 尊重对齐插图作为图像视图内部内容大小的贡献者。
使用情况示例:
在我的应用程序中,我有一个垂直堆栈,由一个小型中心对齐的 UILabel 以及位于 UITableViewCell 中的 UIImageView 组成。标签宽度因单元格而异,导致相应的垂直堆栈宽度发生变化,并使图像的相应水平对齐方式发生偏移。也就是说,在通过水平对齐插图来填充图像时,强制垂直堆栈具有比最大预期标签宽度更大的一致宽度,从而保持表格中图像的垂直居中对齐。

0
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接