Reputation: 50727
I am able to return the screen size using:
- (void) getScreenResolution {
NSArray *screenArray = [NSScreen screens];
NSScreen *mainScreen = [NSScreen mainScreen];
unsigned screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
NSScreen *screen = [screenArray objectAtIndex: index];
NSRect screenRect = [screen visibleFrame];
NSString *mString = ((mainScreen == screen) ? @"Main" : @"not-main");
NSLog(@"Screen #%d (%@) Frame: %@", index, mString, NSStringFromRect(screenRect));
}
}
Output:
Screen #0 (Main) Frame: {{0, 4}, {1344, 814}}
Is there a way to format {1344, 814}
to 1344x814
?
This works perfectly:
- (NSString*) screenResolution {
NSRect screenRect;
NSArray *screenArray = [NSScreen screens];
unsigned screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
NSScreen *screen = [screenArray objectAtIndex: index];
screenRect = [screen visibleFrame];
}
return [NSString stringWithFormat:@"%.1fx%.1f",screenRect.size.width, screenRect.size.height];
}
Upvotes: 37
Views: 46262
Reputation: 236548
edit/update
Swift 4
NSScreen.main?.frame // {x 0 y 0 w 1,920 h 1,200}
NSScreen.main?.frame.width // 1,920.0
NSScreen.main?.frame.height // 1,200.0
Swift 3.x
NSScreen.main()?.frame // {x 0 y 0 w 1,920 h 1,200}
NSScreen.main()?.frame.width // 1,920.0
NSScreen.main()?.frame.height // 1,200.0
Swift 2.x
NSScreen.mainScreen()?.frame // {x 0 y 0 w 1,920 h 1,200}
NSScreen.mainScreen()?.frame.width // 1,920.0
NSScreen.mainScreen()?.frame.height // 1,200.0
Upvotes: 11
Reputation: 1478
In Swift 4.0 you can get the screen size of the main screen:
if let screen = NSScreen.main {
let rect = screen.frame
let height = rect.size.height
let width = rect.size.width
}
If you look for the size of the screen with a particular existing window you can get it with:
var window: NSWindow = ... //The Window laying on the desired screen
var screen = window.screen!
var rect = screen.frame
var height = rect.size.height
var width = rect.size.width
Upvotes: 28
Reputation: 231
Finding the screen size in Mac OS is very simple:
NSRect e = [[NSScreen mainScreen] frame];
H = (int)e.size.height;
W = (int)e.size.width;
Upvotes: 20
Reputation: 71
For those guy who are looking for a way to get screen resolution:
If you are programming a window based app, you can simply get the resolution from _window.screen.frame.size
Upvotes: 7