Как узнать разрешение экрана linux

от admin

xrandr

xrandr is an official configuration utility to the RandR (Resize and Rotate) X Window System extension. It can be used to set the size, orientation or reflection of the outputs for a screen. For configuring multiple monitors see the Multihead page.

Installation

Graphical front-ends

  • ARandR — Simple visual front end for XRandR. Relative monitor positions are shown graphically and can be changed in a drag-and-drop way.
  • LXRandR — Screen resolution and monitor position tool for LXDE. Also works in Openbox.

CLI front-ends

  • autorandr — Automatically select a display configuration based on connected devices.
  • xlayoutdisplay — Detects and arranges displays. Handles: laptop lid state, highest available refresh rates, calculating and applying the actual DPI. Best used in .xinitrc, then can be invoked when plugging/unplugging monitors or closing laptop lid.

Testing configuration

When run without any option, xrandr shows the names of different outputs available on the system ( VGA-1 , HDMI-1 , etc.) and resolutions available on each, with a * after the current one and a + after the preferred one :

You can use xrandr to set different resolution (must be present in the above list) on some output:

When multiple refresh rates are present in the list, it may be changed by the —rate option, either at the same time or independently. For example:

The —auto option will turn the specified output on if it is off and set the preferred (maximum) resolution:

It is possible to specify multiple outputs in one command, e.g. to turn off HDMI-1 and turn on HDMI-2 with preferred resolution:

  • Changes you make using xrandr will only last through the current session.
  • xrandr has a lot more capabilities — see xrandr(1) for details.

Configuration

xrandr is just a simple interface to the RandR extension and has no configuration file. However, there are multiple ways of achieving persistent configuration:

  1. The RandR extension can be configured via X configuration files, see Multihead#RandR for details. This method provides only static configuration.
  2. If you need dynamic configuration, you need to execute xrandr commands each time X server starts. See Autostarting#On Xorg startup for details. This method has the disadvantage of occurring fairly late in the startup process, thus it will not alter the resolution of the display manager if you use one.
  3. Custom scripts calling xrandr can be bound to events (for example when external monitor is plugged in), see udev or acpid for details. The #Scripts section provides you with some example scripts that might be useful for this purpose.

Scripts

Toggle external monitor

This script toggles between an external monitor (specified by $extern ) and a default monitor (specified by $intern ), so that only one monitor is active at a time.

The default monitor should be connected when running the script, which is always true for a laptop.

Manage 2-monitors

mons AUR is a POSIX-compliant shell script to quickly manage 2-monitors display.

It provides well-known modes like computer, duplicate, extend and projector mode as well as selecting and positioning one or two monitors among those plugged in (for more details, see mons).

Avoid X crash with xrasengan

Use this workaround to turn on connected outputs that may be in suspend mode and hence shown as disconnected, as is often the case of DisplayPort monitors:

xrasengan AUR is an xrandr wrapper with this workaround built in.

With the —force option, xrasengan will update status of all outputs before HDMI-0 is turned off, avoiding an X crash if they were the only connected/active outputs.

To force reload current settings, xrasengan provides a —try-reload-active-layout option, which uses —force and unxrandr from the arandr package to assemble the command line:

This can be used in systemd unit or in a keyboard binding to avoid blank screen when resuming DisplayPort monitors from suspend.

Configuration using arandr

arandr can graphically arrange your monitors, change resolutions, and save a script to duplicate your setup. By default, if you «Save As» it will be saved in

/.screenlayout/ . These files can then be autostarted. Sometimes problems arise from running the arandr script too soon after login, add a sleep command if needed.

Troubleshooting

Screen Blinking

For some LCD screens (e.g. Samsung 2343NW, Acer XB280HK and Iiyama ProLite XUB3490WQSU-B1) the command cvt -r can be used to calculate standardized modelines with reduced blanking, allowing for higher frequency signals.

For example: an external monitor ProLite XUB3490WQSU-B1 connected to a Dell laptop through a Thunderbolt-HDMI 2.0 adapter, using 59.97Hz refresh rate with a blinking problem:

Calculating the reduced modelines for the desired resolution cvt -r 3440 1440 gives:

# 3440×1440 59.97 Hz (CVT) hsync: 88.82 kHz; pclk: 319.75 MHz Modeline «3440x1440R» 319.75 3440 3488 3520 3600 1440 1443 1453 1481 +hsync -vsync

With this information we can use xrandr to create a new mode:

xrandr —newmode «3440x1440R» 319.75 3440 3488 3520 3600 1440 1443 1453 1481 +hsync -vsync

And add it to the set of valid modes for the corresponding output to make it selectable:

xrandr —addmode DP1 3440x1440R

Adding undetected resolutions

Due to buggy hardware or drivers, your monitor’s correct resolutions may not always be detected by xrandr. For example, the EDID data block queried from the monitor may be incorrect. To fix this at a low level, see Kernel mode setting#Forcing modes and EDID. This section will describe how to address this at a higher level by adding the desired resolutions to xrandr. This same procedure can be used to add refresh rates you know are supported, but not enabled by your driver.

First we run gtf or cvt to get the Modeline for the resolution we want:

  • If you find that the screen goes blank when the modeline is applied, try lower refresh rate (e.g. 30 or 45 instead of 60). The refresh rate should be passed as the third argument: cvt 2560 1440 45 .

An example for the AMDGPU video driver ( xf86-video-amdgpu ):

Then we create a new xrandr mode. Note that the Modeline keyword needs to be omitted.

After creating it we need an extra step to add this new mode to our current output (VGA1). We use just the name of the mode, since the parameters have been set previously.

Now we change the resolution of the screen to the one we just added:

Note that these settings only take effect during this session.

If you are not sure about the resolution you will test, you may add a sleep 5 and a safe resolution command line following, like this:

Also, change VGA1 to correct output name.

EDID checksum is invalid

If the previous method results in an *ERROR* EDID checksum is invalid error during boot, see KMS#Forcing modes and EDID and [2].

Or xrandr —addmode might give you the error X Error of failed request: BadMatch . NVIDIA users should read NVIDIA/Troubleshooting#xrandr BadMatch. BadMatch could indicate an invalid EDID checksum. To verify that this is the case, run X in verbose mode (e.g. startx — -logverbose 6 ) and check your Xorg log for messages about a bad EDID.

Screen resolution reverts back after a blink

If you use GNOME and your monitor does not have an EDID, above #Adding undetected resolutions might not work, with your screen just blinking once, after xrandr —output .

Poke around with

/.config/monitors.xml , or delete the file completely, and then reboot.

It is better explained in this article.

Permanently adding undetected resolutions

Once a suitable resolution is found using xrandr , the mode can be permanently added by creating an entry in /etc/X11/xorg.conf.d/ :

Replace intel with the right driver, e.g. nvidia . When the X server is restarted, you should be able to set the new resolution.

If this does not work for you, try removing the Screen and Device sections and just leaving the Monitor section. [3]

Resolution lower than expected

If your video card is recognized but the resolution is lower than you expect, you may try this.

Background: ATI X1550 based video card and two LCD monitors DELL 2408(up to 1920×1200) and Samsung 206BW(up to 1680×1050). Upon first login after installation, the resolution default to 1152×864. xrandr does not list any resolution higher than 1152×864. You may want to try editing /etc/X11/xorg.conf, add a section about virtual screen, logout, login and see if this helps. If not then read on.

About the numbers: DELL on the left and Samsung on the right. So the virtual width is of sum of both LCD width 3600=1920+1680; Height then is figured as the max of them, which is max(1200,1050)=1200. If you put one LCD above the other, use this calculation instead: (max(width1, width2), height1+height2).

Setting resolution from .xinitrc doesn’t work

DDX drivers other than that of the modesetting(4) driver may take time to properly enumerate the modes of attached devices, to where xrandr may not work right away. This seems to be the case for the xf86-video-intel driver, with which using xrandr early in the startup sets the incorrect resolution. Possible remedies include:

  • Waiting for a couple of seconds before invoking xrandr:

This does the waiting in the background, as to not block the rest of the startup. If this not desirable, e.g. your window manager configuration depends on the display being arranged correctly, you can execute the commands in the foreground:

  • Setting the mode in a later part of the desktop startup. Refer to your window manager documentation for details on startup script functionality.
  • Switching to the generic modesetting driver. This is most easily done by uninstalling the device specific DDX driver. In the case of xf86-video-intel , the driver has other deficiencies that may benefit from this; see Intel graphics#Installation for more information.

Correction of overscan tv resolutions via the underscan property

With a flat panel TV, w:overscan looks like the picture is «zoomed in» so the edges are cut off.

Check your TV if there is a parameter to change. If not check if the output has support for the underscan property (xrandr —prop), if so apply an underscan and change border values. The required underscan vborder and underscan hborder values can be different for you, just check it and change it by more or less.

Correction of overscan tv resolutions via —transform

If underscan is not available another solution is using xrandr —transform a,b,c,d,e,f,g,h,i , which applies a transformation matrix on the output. See the xrandr(1) § RandR_version_1.3_options manual page for the explanation of the transformation.

For example, the transformation scaling horizontal coordinates by 0.8 , vertical coordinates by 1.04 and moving the screen by 35 pixels right and 19 pixels down, is:

Читать:
Для чего нужен трансивер

Disabling phantom monitor

In some cases, a non-existent monitor may be detected by the system. To disable it, find the name of the phantom output, e.g. VGA1, and turn it off with

To make this permanent, add the following to an entry in /etc/X11/xorg.conf.d/ :

Dynamic interlace pattern artifacts with AOC G2590PX

If you are seeing very prominent interlace pattern artifacts (mesh or grid) when you see movement on the screen with this monitor, it might be happening because of a low refresh rate. Switching to a higher refresh rate (from 60 Hz to 119.98 Hz and perhaps even higher) might help reduce the effect.

Sample xrandr output for this monitor over HDMI:

As can be seen in the output above, the preferred refresh rate reported by xrandr is 60.00, but the artifacts are very visible with this refresh rate. Switching to 119.98 should help reduce the effect considerably.

Разрешение экрана в Linux

С развитием технологий экраны для компьютеров смогли значительно увеличить разрешение. Если старые экраны показывали 640х800 пикселей, то более новые отображают уже 1920х1080. У последних моделей разрешение ещё выше.

В операционной системе Linux существует несколько способов настройки разрешения экрана. В обычных системах, как правило, это не нужно. Но если вы хотите использовать несколько мониторов или решили запустить Linux на виртуальной машине, то разрешение может определиться неправильно и тогда придётся его настроить. В этой статье мы рассмотрим, как изменить разрешение экрана в Linux через графический интерфейс и терминал.

Настройка разрешения экрана в GUI

Разберём настройку разрешения на примере дистрибутива Ubuntu и окружения рабочего стола Gnome. Откройте утилиту Настройки из главного меню:

Перейдите на вкладку Устройства, а затем выберите пункт Настройка экранов:

Если к компьютеру подключено два монитора Linux или больше, то у вас будет три варианта работы экранов:

  • Объединение — все экраны объединяются в одно рабочее пространство;
  • Зеркальное отображение — одинаковая картинка на всех экранах;
  • Один экран — картинка только на одном экране, другие отключены.

Независимо от того, какой режим вы выбираете, будут доступны настройки Разрешение и Частота обновления, где вы сможете настроить нужные вам параметры:

Так выполняется настройка монитора Linux через графический интерфейс. Если вы хотите объединить экраны, то можно указать разрешение мониторов Linux для каждого из них отдельно:

Но здесь есть один недостаток, вы можете выбрать только то разрешение экрана, которое предлагает система. Если вы захотите установить разрешение выше или ниже тех, что есть, то у вас ничего не выйдет. Для этого надо воспользоваться терминалом.

Как изменить разрешение экрана через терминал

Для управления настройками экрана из терминала можно использовать утилиту xrandr. Синтаксис утилиты очень прост:

xrandr опции параметры

Разберём основные опции утилиты, которые будем использовать:

  • —verbose — включить более подробный вывод;
  • —version — версия программы;
  • —query — когда установлена эта опция или не указанно никаких опций, выводится текущая конфигурация;
  • -d, —display — позволяет указать какой X экран использовать по имени;
  • -s, —screen — устанавливает дисплей для настройки по ID;
  • —output — устанавливает дисплей для настройки по имени или ID;
  • —primary — выбрать основной экран;
  • —size — позволяет указать размер экрана;
  • —rate — устанавливает частоту обновления;
  • —dpi — устанавливает DPI, количество точек на дюйм, которое позволяет вычислить правильный размер для окон;
  • —newmode — создаёт новый режим отображения по размеру и частоте;
  • —rmmode — удаляет режим отображения;
  • —addmode — добавляет созданный режим к списку доступных для использования;
  • —delmode — удалить режим из списка доступных;
  • —mode — активирует указанный режим;
  • —off — отключает экран;
  • —gamma — позволяет установить коррекцию гаммы, в формате красный:зеленый:синий;

Чтобы посмотреть текущие параметры системы, запустите утилиту без параметров:

Как видите, к моей системе подключено два экрана:

  • LVDS-1 — встроенный экран ноутбука;
  • HDMI-1 — внешний экран;

Для каждого экрана доступно несколько разрешений, текущее разрешение отмечено звёздочкой. Чтобы изменить разрешение экрана Linux на одно из доступных, используйте опцию —mode вместе с —output:

xrandr —output HDMI-1 —mode 1680×1050

Теперь звёздочка выводится около разрешения 1680х1050.

Хорошо, мы разобрались с тем, как добавить одно из существующих разрешений. По сути, то же самое, что и в графическом интерфейсе. Но если нужного разрешения в списке нет, то его можно добавить. Для этого сначала нужно конвертировать обычную запись в формат VESA. Для этого используйте утилиту cvt. Например, создадим режим с разрешением 2000х1100 и частотой обновления 60:

cvt 2000 1100 60

Дальше надо скопировать из вывода утилиты всё, что написано после «Modeline». Осталось использовать скопированный текст в xrandr:

xrandr —newmode «2000x1100_60.00» 183.75 2000 2136 2344 2688 1100 1103 1113 1141 -hsync +vsync

Добавляем только что созданное разрешение к списку доступных для нужного нам экрана:

xrandr —addmode HDMI-1 2000x1100_60.00

А затем активируем, как описывалось выше:

xrandr —output HDMI-1 —mode 2000x1100_60.00

Но будьте аккуратны с новыми разрешениями. Если вы устанавливаете разрешение выше, чем поддерживает ваш монитор, то он просто не будет показывать. Но такая штука может быть полезна с VirtualBox, или если компьютер не определяет, что ваш монитор поддерживает более высокое разрешение.

Чтобы сохранить настройки после перезагрузки, добавьте команду активации разрешения в конфигурационный файл

Синтаксис файла очень похож на

/.xinitrc. Все команды из него автоматически выполняются при старте сессии. Или же вы можете использовать любой другой метод автозагрузки, который работает после запуска X.

Выводы

В этой статье мы рассмотрели несколько способов настроить разрешение экрана Linux с помощью графического интерфейса или через терминал. Как видите, это не так сложно, как может показаться на первый взгляд.

Похожие записи

Оцените статью

alt=»Creative Commons License» width=»» />
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

28 комментариев к “Разрешение экрана в Linux”

может кому и пригодится, если больше не о чем

У меня реально проблема до конца не решена с подключением 4к телевизора LG 49 inches к ПК по hdmi кабелю .Испробовал все самые известные дистрибутивы остановился на ubuntu 18.04 хотя заметил не столько в дистре проблемы сколько в DE .GTK еще как то более адекватно работают на отрытых драйверах с 49 inches дисплеем а QT сколько намучился что то свыше 32 inches все никак не получается настроить . На нуво драйвере хотя бы разрешение можно установить приемлемое,но есть тиринг проблема с маштабированием и прочие огрехи .Сразу поставил проприетарный nvidia драйвер так телевизор с ПК отказываются дать желаемый результат .То изображение не тот маштаб экрана то картинка рябит не качественная ,на этом же компе 2 система винда 10 определяет отлично автоматом . А в Linux нуво еще как то можно ручками настроить , nvidia драйвер вообще жесть .Больше всего бесит если используешь приемлемое разрешение например 1920×1080 то картинка не влезает в экран или стоит косо или шрифты смазываются .Вообщем пока мес открый драйвер ну более менее .Но это факт кто подключает более большие мониторы или телевизоры .

Очень рекомендую автору:
1) Создать список тем по софту и железу;
2) Провести опрос среди посетителей сайта;
3) На основании этого опроса строить свою дальнейшую политику! )))
Пишите — и мы напишем Вам нужные статьи )))
На самом деле — все очень просто)))

Да можно было бы сделать из контента а контент у этого автора мне нравится много интересного прочитал почерпнул можно было сделать более активный и полезный если не форум ,но комментарии для помощи ,тем более линуксоподобные системы у нас в руках .

unixforum.org

Решено: Как узнать текущее разрешение экрана из консоли?

Модератор: Bizdelnick

Решено: Как узнать текущее разрешение экрана из консоли?

Сообщение zshgm » 04.07.2010 17:57

Как узнать текущее разрешение экрана из КОНСОЛИ?

В /etc/X11/xorg.conf сразу несколько допустимых разрешений экрана, а как узнать текущее?

Section "Screen"
Identifier "Default Screen"
Device "Intel Corporation 82915G/GV/910GL Integrated Graphics Controller"
Monitor "LCD73V"
DefaultDepth 24
SubSection "Display"
Depth 1
Modes "1280×1024" "1152×864" "1024×768" "832×624" "800×600" "720×400" "640×480"
EndSubSection
.

How can I get the monitor resolution using the command line?

I would like to find a wallpaper that best suits my resolution. How can I get the resolution just by writing commands in the command line?

10 Answers 10

Or to get just the resolution:

aguslr's user avatar

I would just use xrandr :

Here I have two screens, the resolution are:

  • 1600×900 (laptop)
  • 1920×1200 (monitor)

To get only the resolution of your primary monitor, you can also use this python oneliner:

To get the resolution of your extanded desktop (for a multi monitor setup):

Sylvain Pineau's user avatar

The request was for the resolution. That is given by

muru's user avatar

You can also use:

Example of output on one of my machines:

Billal Begueradj's user avatar

On a raspberry pi without X, I was able to get the screen resolution by running:

Anonymous Platypus's user avatar

You can get your current screen’s resolution as follows:

Get the X resolution by running:

Get the Y resolution by running:

Output the X and Y resolution by running:

That should be possible to do like this without using awk too.

One alternate way is:

You can start by terminal your preferred website which show you your screen resolution.

You can show the webpage on your terminal too by useing https://www.brow.sh/

If you like, you can skrapping this page by terminal by include appropriate python website skrapping tools and export the output to a terminal var.

Another solution is to use xprop:

If anyone cares, it was slightly faster on my machine than grepping xdpyinfo

Or, if you only care about width:

Tested only on multiple displays organized via Xinerama.

For what it’s worth, when using multiple connected displays and/or offsets with TwinView then xdpyinfo will give you the resolution of the entire set of displays the way they are configured. If you require the resolution of a single monitor or a monitor connected to one of the display ports you need to use xrandr. However, even in that configuration xrandr can be unreliable and not show the resolution. See this example entry from my X windows config file:

The xrandr output looks like this:

You can see that DP-3 isn’t showing a resolution on the line that a grep for «connected» would show. So the best, most consistent, and reliable command I’ve found for identifying the resolution of any individual connected display is:

which produces this:

At that point, it’s pretty trivial to pick out the different resolutions or grep for only one port.

Похожие статьи