How can I get the screen resolution in R

落花浮王杯 提交于 2019-12-10 12:32:37

问题


How can I get screen resolution (height, width) in pixels?


回答1:


You could use commad-line interface to WMI

> system("wmic desktopmonitor get screenheight")
ScreenHeight  
900   

You could capture result with system

(scr_width <- system("wmic desktopmonitor get screenwidth", intern=TRUE))
# [1] "ScreenWidth  \r" "1440         \r" "\r"
(scr_height <- system("wmic desktopmonitor get screenheight", intern=TRUE))
# [1] "ScreenHeight  \r" "900           \r" "\r" 

With multiple screens, the output is, e.g.,

[1] "ScreenWidth  \r" "1600         \r" "1600         \r" ""

We want all but the first and last values, converted to numbers

as.numeric(c(
  scr_width[-c(1, length(scr_width))], 
  scr_height[-c(1, length(scr_height))]
))
# [1] 1440  900



回答2:


It's easy with JavaScript: you just do

window.screen.height
window.screen.width

You can call JavaScript from R using the SpiderMonkey package from OmegaHat.


You could also solve this with Java, and use the rJava package to access it.

library(rJava)
.jinit()
toolkit <- J("java.awt.Toolkit")
default_toolkit <- .jrcall(toolkit, "getDefaultToolkit")
dim <- .jrcall(default_toolkit, "getScreenSize")
height <- .jcall(dim, "D", "getHeight")
width <- .jcall(dim, "D", "getWidth")



回答3:


Accepted answer does not work on Windows 8 and later.

Use this:

system("wmic path Win32_VideoController get VideoModeDescription,CurrentVerticalResolution,CurrentHorizontalResolution /format:value")

To get you screen resolution in a vector, you can implement it as:

  suppressWarnings(
    current_resolution <- system("wmic path Win32_VideoController get CurrentHorizontalResolution,CurrentVerticalResolution /format:value", intern = TRUE)  %>%
      strsplit("=") %>%
      unlist() %>%
      as.double()
  )
  current_resolution <- current_resolution[!is.na(current_resolution)]

Now you'll have a vector with length 2:

> current_resolution
[1] 1920 1080



回答4:


On Windows you can call GetSystemMetrics passing SM_CXSCREEN and SM_CYSCREEN. This returns the width/height of the screen of the primary display monitor, in pixels.

DWORD dwWidth = GetSystemMetrics(SM_CXSCREEN);
DWORD dwHeight = GetSystemMetrics(SM_CYSCREEN);


来源:https://stackoverflow.com/questions/7305244/how-can-i-get-the-screen-resolution-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!