在UIImageView周围填充. Swift 3

sf6xfgos  于 2023-03-11  发布在  Swift
关注(0)|答案(6)|浏览(110)

我有一个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)

我读了很多关于这个的文章,但是这些是我找到的解决方案,但是它们不起作用。
非常感谢。

kx5bkwkv

kx5bkwkv1#

Swift 4.2和5

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

插入值应为负值

hmae6n7t

hmae6n7t2#

您可以将imageView插入到视图中,并设置对边的约束,保证方法:)

xxhby3vn

xxhby3vn3#

在新类中重写alignmentRectInsets属性:

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

qyyhg6bp4#

下面是我构建的一个小助手扩展:

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

gtlvzcf85#

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

idv4meu86#

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将对齐插图视为图像视图固有内容大小的贡献者。
`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.`

相关问题