【问题标题】:How do you adjust an image's size to NSImageView programmatically?如何以编程方式将图像的大小调整为 NSImageView?
【发布时间】:2021-04-28 17:31:25
【问题描述】:

我一直在尝试以编程方式调整NSImageView 中的图像大小。似乎没有任何方法可以这样做。图像最终变得非常大,无法调整。我想将其调整为 40(宽)乘 40(高)。

这是以编程方式创建的图像视图:

let theImg: NSImageView = {
    let imageView = NSImageView()
    imageView.image = NSImage(named: "my-logo")
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

以下是图像的约束:

view.addSubview(theImg)
theImg.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 280).isActive = true
theImg.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
theImg.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true

如果可能的话,我会很感激那些愿意提供帮助或至少提供一些提示的人。

【问题讨论】:

标签: swift macos appkit nsimage nsimageview


【解决方案1】:

你可以像这样将它添加到你的约束中:

NSLayoutConstraint.activate([
            theImg.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 280),
            theImg.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            theImg.topAnchor.constraint(equalTo: view.topAnchor, constant: 50),
            theImg.widthAnchor.constraint(equalToConstant: 40),
            theImg.heightAnchor.constraint(equalToConstant: 40)
        ])

NSLayoutConstraint.activate 是一种更好的激活/停用约束的方法,因为您可以使用一组约束并停用/激活它们,而不是一个一个地设置isActive

此外,除非您希望左/前约束位于左侧,即使是从右到左的语言,您应该使用 leadingAnchor 而不是 leftAnchorMore info

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    相关资源
    最近更新 更多