首页 文章

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

提问于
浏览
0

我有一个带有CALayer的NSView(myImage),contents =一个NSImage,所以视图的大小现在已经完全适合NSImage(大小未知且可能会有变化) . 这是另一个NSView(myContainer)内部,它固定在两个轴上独立展开和收缩 .

所以我喜欢这个行为就像NSImageView设置为“按比例缩小” . 在调整大小时,在“myContainer”视图的范围内保持完全可见,并且在我将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目前固定在其超视图的四周 . 这给了我与“按比例上下比例”的NSImage视图相同的行为 . 但我只想“按比例缩小” . 所以我觉得我必须将保持图层的NSView的宽度和高度限制为从图层中使用的原始图像中检索到的最大宽度和高度 . 但如何实现这一目标正在暗示着我 .

enter image description here

1 回答

  • 0

    想出最后一块拼图 . 在我的问题中加上上面的代码:( 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()
    }
    

相关问题