0
votes

I have an NSView (myImage) with a CALayer, contents = an NSImage, so the view has now been sized to fit the NSImage exactly (size unknown and subject to change). This is inside another NSView (myContainer) that is pinned to expand and contract in both axis independently.

So I'd love this to behave like an NSImageView set to "scale proportionately down". to stay fully visible within the bounds of "myContainer" view as it resizes, and never get larger that the size it was created at the time I added the NSImage to its CALayer.

Possible in IB only? Not sure, but even with a mixture of IB created constraints and constraints generated and amended when the app is running, I can't get this to work just like an NSImageView does. Please help.

EDIT WITH PROGRESS
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
}

The NSView with the layer is currently pinned on all sides to its superview. This gives me the same behaviour as an NSImage view in "scale proportionately up and down". But I only want "scale proportionately down". So I feel I must restrict the width and height of the NSView that holds the layer to a max width and height as retrieved from the original image used in the layer. But how to achieve this is alluding me.

enter image description here

1

1 Answers

0
votes

Figured the final piece of the puzzle out. Coupled with the code above in my question : (currentImageRealWidth is stored as a variable at the time the user added their image).

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()
}