我可以使用以下方法返回屏幕尺寸:
- (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));
}
}
输出:
屏幕#0(主要)框架:{{0,4},{1344,814}}
有没有办法将{1344, 814}
格式化为 1344x814
?
这非常有效:
- (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];
}
答案 0 :(得分:17)
在Mac OS中查找屏幕尺寸非常简单:
NSRect e = [[NSScreen mainScreen] frame];
H = (int)e.size.height;
W = (int)e.size.width;
答案 1 :(得分:14)
在Swift 4.0中,您可以获得主屏幕的屏幕尺寸:
if let screen = NSScreen.main {
let rect = screen.frame
let height = rect.size.height
let width = rect.size.width
}
如果您使用特定的现有窗口查找屏幕大小,可以使用以下方法获取:
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
答案 2 :(得分:12)
NSLog(@"%fx%f",screenRect.size.width, screenRect.size.height);
答案 3 :(得分:7)
对于那些正在寻找获得屏幕分辨率的人:
如果您正在编写基于窗口的应用程序,则只需从_window.screen.frame.size获取分辨率
答案 4 :(得分:4)
编辑/更新
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
答案 5 :(得分:0)
Swift 3解决方案:
NSScreen.main()!.frame