Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

swift - How do you adjust an image's size to NSImageView programmatically?

I have been trying to adjust an image's size in NSImageView programmatically. There doesn't seem to be any way to do so. The image ends up being quite large and there is no way to adjust it. I want to adjust it to a 40 (width) by 40 (height).

Here is the image view created programmatically:

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

Here are the constraints for the image:

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

I'd appreciate those who would be willing to help or at least give some hints if possible.

question from:https://stackoverflow.com/questions/65875819/how-do-you-adjust-an-images-size-to-nsimageview-programmatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add it to your constraints like this:

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 is a better approach to activate/deactivate constraints, because you can use an array of constraints and deactivate/activate them, instead of setting isActive one by one.

Also, unless you want your left/leading constraint to be on the left, even on right to left languages, you should use leadingAnchor instead of leftAnchor. More info


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...