Finding an NSView's current magnification.

Q: How can I find out what the current scale of an NSView's coordinate space is, if it's been changed from the default?

A: NSView provides a method, -convertSize:fromView:, to convert sizes between the coordinate spaces of various views in a window. If you convert a known size from the window's base coordinate space to that of your NSView, the result is the current zoom level.

Another NSView method, -scaleUnitSquareToSize:, sets the magnification relative to the view's existing coordinate system. By using an Objective-C category to add few methods NSView, we can provide a convenient API to scale NSView instances in absolute terms.

Listing 1: ScaleUtilities category declaration

@interface NSView (ScaleUtilities)

- (NSSize) scale;
- (void) setScale:(NSSize) newScale;
- (void) resetScaling;

- (float) scalePercent;
- (void) setScalePercent:(float) scale;


Listing 2: ScaleUtilities category implementation

@implementation NSView (ScaleUtilities)

const NSSize unitSize = { 1.0, 1.0 };

  // This method makes the scaling of the receiver equal to the window's
  // base coordinate system.
- (void) resetScaling { [self scaleUnitSquareToSize: [self convertSize: unitSize fromView: nil]];  }

  // This method sets the scale in absolute terms.
- (void) setScale:(NSSize) newScale
  [self resetScaling];  // First, match our scaling to the window's coordinate system
  [self scaleUnitSquareToSize:newScale]; // Then, set the scale.

  // This method returns the scale of the receiver's coordinate system, relative to
  // the window's base coordinate system.
- (NSSize) scale { return [self convertSize:unitSize toView:nil]; }

// Use these if you'd rather work with percentages.
- (float) scalePercent { return [self scale].width * 100; }

- (void) setScalePercent:(float) scale
  scale = scale/100.0;
  [self setScale:NSMakeSize(scale, scale)];
  [self setNeedsDisplay:YES];


Document Revision History

2005-03-08Fixed a typo in the captions for the listings.
2004-12-13There was a mistake in the implementation of -resetScaling. I was doing a -convertSize:toView: that should have been a -convertSize:fromView:
2004-10-14How to discover the current magnification (zoom level) of any NSView.

Posted: 2005-03-08

Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.