zekel
zekel

Reputation: 9457

How do you position a larger NSImage inside of a smaller NSImageView programmatically?

Let's say I have an NSImage that's 100x100. I also have an NSImageView that's 50x50. Is there a way I can place the NSImage at coordinates inside the NSImageView, so I can control which part of it shows? It didn't seem like NSImage had an initWithFrame method...

Upvotes: 1

Views: 1674

Answers (5)

silverdr
silverdr

Reputation: 2172

Depends on what your eventual goal is but the easiest thing to me seems to put your NSImageView inside an NSView (or a subclass – doesn't have to be NSScrollView as "@NSResponder" user suggests but this should work well too), set its imageScaling to NSImageScaleProportionallyUpOrDown and its frameSize to image's size. Then you can move your NSImageView freely around the upper view using setFrame:myDesiredFrame. No subclassing, no manual redrawing, etc.

Upvotes: 0

Lily Ballard
Lily Ballard

Reputation: 185671

NSImageView has a method -setImageAlignment: which lets you control how the image is aligned within the image view. Unfortunately, if you want to display part of the image that doesn't correspond to any of the NSImageAlignment values, you're going to have to draw the image programmatically.

Upvotes: 1

NSResponder
NSResponder

Reputation: 16861

Make your imageview as big as the image, and put it inside a scrollview. Hide the scrollers if you want. No need for subclassing in this case.

Upvotes: 1

zekel
zekel

Reputation: 9457

I did this in my NSImageView subclass, as Andrew suggested.

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];
    NSRect cropRect = NSMakeRect(x, y, w, h);
    [image drawAtPoint:NSZeroPoint
              fromRect:cropRect
             operation:NSCompositeCopy
              fraction:1];
}

Upvotes: 3

Andrew Grant
Andrew Grant

Reputation: 58796

I don't believe so, but it's trivial to roll your own NSImageView equivalent that supports center/stretch options by drawing the image yourself.

Upvotes: 2

Related Questions