gpt4 book ai didi

swift - 布局约束使 NSView 的行为类似于 NSImageView 中的 NSImage

转载 作者:行者123 更新时间:2023-11-30 13:28:18 26 4
gpt4 key购买 nike

我有一个带有 CALayer 的 NSView (myImage),内容 = NSImage,因此 View 的大小现已调整为完全适合 NSImage(大小未知且可能会更改)。这是在另一个 NSView (myContainer) 内,该 NSView 被固定以独立地在两个轴上扩展和收缩。

所以我希望它的行为就像 NSImageView 设置为“按比例缩小”。在调整大小时在“myContainer” View 的范围内保持完全可见,并且永远不会大于我将 NSImage 添加到其 CALayer 时创建的大小。

仅在 IB 中可能吗?不确定,但即使混合了 IB 创建的约束以及应用程序运行时生成和修改的约束,我也无法像 NSImageView 那样工作。请帮忙。

编辑有进展
func newUserImageInputDidArrive() -> Void {
// the real widh and height of the NSImage we will add to layer of NSView
currentImageRealWidth = (mainImageDropZone.image?.size.width)!
currentImageRealHeight = (mainImageDropZone.image?.size.height)!
// set the width of NSView to match above
mainImageView.frame.size.width = currentImageRealWidth
mainImageView.frame.size.height = currentImageRealHeight
// create the layer in the NSView
mainImageView.wantsLayer = true
mainImageView.layer?.borderColor = NSColor.redColor().CGColor
mainImageView.layer?.borderWidth = 5
// so the image added to the layer will resize proportionately within the bounds of the layer
mainImageView.layer?.contentsGravity = kCAGravityResizeAspect
// add the image
mainImageView.layer?.contents = mainImageDropZone.image
// so now NSView's layer has the image and is the size of the origonal image
}

带有该层的 NSView 目前在所有方面都固定到其 super View 。这给了我与“按比例向上和向下缩放”中的 NSImage View 相同的行为。但我只想“按比例缩小”。所以我觉得我必须限制 NSView 的宽度和高度,该 NSView 将图层保持为从图层中使用的原始图像检索到的最大宽度和高度。但如何实现这一点正在暗示我。

enter image description here

最佳答案

解决了最后一 block 拼图。加上我的问题中上面的代码:(currentImageRealWidth 在用户添加图像时存储为变量)。

override func viewWillLayout() {
if(mainImageView.layer != nil){
if(mainImageView.layer?.frame.width > currentImageRealWidth){
conMainImageViewLeading.constant = (mainContentView.frame.width - currentImageRealWidth) / 2
conMainImageViewTrailing.constant = (mainContentView.frame.width - currentImageRealWidth) / 2
}else{
conMainImageViewLeading.constant = 0
conMainImageViewTrailing.constant = 0
}
}
super.viewWillLayout()
}

关于swift - 布局约束使 NSView 的行为类似于 NSImageView 中的 NSImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com