objective-ccocoansimagensscrollviewnsimageview

NSImageView resized with image size


I'm new to Obj-C/Cocoa programming and facing to a problem about NSImageView.
My goal is to create an app which allow the user to put an image on it with drag&drop.

The problem is the following : when we're dropping an image larger than the window, it resizes the window to the image size, I don't want that !
I put my NSImageView into a NSScrollView so only a certain part of the image MUST be showed and the user will move sliders to view the entire one (or simply resize the window), that's what I want..

Here is my XIB hierarchy (concerned part) :


In the code of my NSImageView, I have (about that problem) :

[self setImageScaling:NSScaleProportionally];
[self setImage:newImage];


NOTE: The sliders seem to move the view and not the image
NOTE2: I can't resize the window to a lower size than the image


Solution

  • I have a horrible aversion to nib files and prefer to do things programmatically whenever possible so I'm not much help with that... but here's a little listing from a little NSScrollview test app I recently coded up that does something similar. The only non-self-contained thing mentioned in this code chunk is the window name, which refers to an NSWindow * for a window that was already created. And self here just refers to a controller object.

    NSImage * myImage       = [NSImage imageNamed:@"myfilename.png"];
    NSRect imageRect        = NSMakeRect(0.0,0.0,myImage.size.width,myImage.size.height);
    
    
    self.myImageView        = [[NSImageView alloc] initWithFrame:imageRect];
    self.myImageView.bounds = imageRect;
    self.myImageView.image  = myImage;
    
    self.myScrollView       = [[NSScrollView alloc] initWithFrame:[window.contentView frame]];
    self.myScrollView.hasVerticalScroller = YES;
    self.myScrollView.hasHorizontalScroller = YES;
    self.myScrollView.documentView = self.myImageView;
    self.myScrollView.borderType = NSNoBorder;
    self.myScrollView.scrollerStyle = NSScrollerStyleOverlay;
    
    window.contentView      = self.myScrollView;
    

    I know that's perhaps not the solution you were looking for but maybe it helps you debug? In particular, I didn't do anything funny with my NSImageView besides give it a frame, a bounds rectangle, and an NSImage *, so I don't think you need to worry about the scaling parameter per se -- in fact, if you want the image to be full-sized and to scroll around it, you want your NSImageView's frame to be the same size as the image so that it doesn't HAVE to scale at all. Maybe that's your problem -- the frame is too small? It is OK for the NSImageView frame to be bigger than the window -- that's what lets you scroll around it.