【问题标题】:How can I get all supported screen resolutions on mac OSX Swift如何在 mac OSX Swift 上获得所有支持的屏幕分辨率
【发布时间】:2015-10-25 03:39:57
【问题描述】:

我想要一个代码

1) 获取我当前的屏幕分辨率,(已解决)。

例如:获取当前屏幕显示代码为:

system_profiler SPDisplaysDataType |grep 分辨率

2)抓取所有支持的分辨率,如下图所示(未解决)。

或者任何 Objective C 代码也有用

【问题讨论】:

  • 描述您的要求并要求某人为您编写代码、解释如何编写代码或提供示例或参考的问题是题外话。请确定有关编程的特定问题或问题。包括尝试的解决方案、结果与预期结果有何不同的解释,以及您收到的任何错误消息的全文。请阅读关于提出好问题的建议:[How to Ask]、[Writing the perfect question]。
  • 获取当前屏幕分辨率的代码是--------------- system_profiler SPDisplaysDataType |grep Resolution
  • 请编辑您的问题,不要在 cmets 中发布代码。
  • 感谢您帮助我使问题更清晰
  • @LeoNatan “你想要代码?对你有好处。这是一个糟糕的问题。——Leo Natan 5 小时前”他已经问过这个问题,并且一年多前已经回答了他自己的问题。

标签: objective-c swift macos


【解决方案1】:

Xcode 11 • Swift 5.1

extension CGDirectDisplayID  {
    var displayMode: CGDisplayMode? { CGDisplayCopyDisplayMode(self) }
    func allDisplayModes(options: CFDictionary? = nil) -> [CGDisplayMode] { CGDisplayCopyAllDisplayModes(self, options) as? [CGDisplayMode] ?? [] }
}

extension CGDisplayMode {
    var resolution: String { .init(width) + " x " + .init(height) }
}

struct Display {
    static var main: CGDirectDisplayID { CGMainDisplayID() }
    static var mode: CGDisplayMode? { main.displayMode }
    static func allModes(for directDisplayID: CGDirectDisplayID = main) -> [CGDisplayMode] { directDisplayID.allDisplayModes() }
}

用法:

if let resolution = Display.mode?.resolution {
    print("Resolution:", resolution)
}
for mode in Display.allModes() {
    print(mode.resolution)
}

【讨论】:

    【解决方案2】:

    Swift 代码

        var displayConfig: CGDisplayConfigRef = nil
        let mainDisplayID = CGMainDisplayID()
    
        var displayMode = CGDisplayCopyDisplayMode(mainDisplayID).takeRetainedValue()
        var width = CGDisplayModeGetWidth(displayMode)
        var height = CGDisplayModeGetHeight(displayMode)
    
        print("current size: \(width)x\(height)\n")
        print("available sizes:\n")
    
        var modes = CGDisplayCopyAllDisplayModes(mainDisplayID, nil).takeRetainedValue()
        let modesCount = CFArrayGetCount(modes) - 1
    
        for i in 0...modesCount {
            var mode: CGDisplayModeRef = unsafeBitCast(CFArrayGetValueAtIndex(modes, i), CGDisplayModeRef.self)
    
            var width = CGDisplayModeGetWidth(mode)
            var height = CGDisplayModeGetHeight(mode)
            print("\t\(width)x\(height)\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多