Cairo linux что это

Обновлено: 03.07.2024

Привет мой читатель. В предыдущей статье мы установили и выполнили базовую настройку оконного менеджера OpenBox и панели tint2. Я обещал на следующем шаге, то есть уже в этой статье, рассмотреть установку и настройку нескольких вариантов доков и панели статус баров Polybar. Сразу прошу извинить, Polybar мы рассмотрим в одной из следующих статей так как тема доков слишком обширна.

Что же такое ДОК? Это тоже "красивая панелька с иконками". Ниже на скриншоте пример знаменитого дока из MacOS. Панель в нижней части экрана и есть док.

А что же нам доступно в Linux? Давайте посмотрим. Вот краткий список:

Пожалуй достаточно. Вы можете самостоятельно полюбопытствовать на тему доков для Linux и найти ещё много вариантов. А мы сейчас начнём устанавливать доки из нашего списка и разбираться с их возможностями. Но прежде нам нужно установить и запустить какой-нибудь из композитных менеджеров. Как я уже говорил в предыдущей статье, композитный менеджер заведует такими эффектами, как прозрачность и тени. Многие доки их используют, а потому приступим. Самый лёгкий и простой композитный менеджер называется xcompmgr. Установим его командой
sudo apt install xcompmgr

Все его ключи запуска можно глянуть выполнив команду
xcompmgr --help

Позже вы можете самостоятельно поэкспериментировать, а пока открываем для редактирования файл автозапуска OpenBox:
mcedit

/.config/openbox/autostart.sh
и добавляем в него первой строчкой (перед имеющейся командой запуска tint2) команду:
xcompmgr -c &

Сохраняем файл и перезапускаем сессию (выходим в окно приветствия выбрав пункт меню EXIT по правому клику мышки на рабочем столе и логинимся заново).

Чуть не забыл! Вероятно у вас уже есть композитный менеджер и скорее всего это compton . Если это так - просто добавьте его в файл автозапуска OpenBox (не забудьте дописать знак амперсанд " & " после команды).

Теперь установим Cairo Dock. Для этого откроем терминал и выполним команды:

sudo add-apt-repository ppa:cairo-dock-team/ppa

sudo apt-get update

sudo apt-get install cairo-dock cairo-dock-plug-ins

Далее запускаем его командой cairo-dock или находим его в меню приложений. Сразу после установки док имеет вот такой вид:

Cairoglyphics: A tutorial by way of diagrams. From a Python pov. Please help debug them.

Using the PostScript surface: How to use the PostScript surface.

Other information that might be of interest:

Roadmap: Features planned for upcoming release

Todo: Other ideas, (not yet on the roadmap)

Missing: Page listing features missing to allow SVG/Flash rendering using cairo without fallbacks.

Bibliography: Where the good ideas came from

Building: Various recipes for compiling Cairo sources on different platforms, and with different goals

Editing this Website

Currently the cairo website can only be edited via git. You can get the sources by running

Here is a collection of pointers to articles that have been written elsewhere about cairo. Many of these articles might provide good inpiration for generating new primary-source documentation. As we improve the primary documentation to cover the same material that is covered below, we can drop items from the following list, (or at least move the links to some other page).

Tutorials

Cairo Tutorial for Python (and other) Programmers In spite of the name, this tutorial provides a one-of-a-kind introduction to the cairo concepts and models that will be helpful to programmers using cairo from any programming language.

Using Cairo with Xlib How to use Cairo in simple Xlib-based GUI applications, with no Gtk required.

Writing a widget using cairo and GTK+ 2.8 A very clean, short, well-written tutorial by Davyd Madeley. The second-half of this first part gives a reasonable introduction to cairo even for users that are not using GTK+. Davyd's second installment goes into animating the example. There's not nearly as much cairo-specific detail there, but it's worth mentioning it here for completeness.

Writing a widget using cairo and PyGTK 2.8 a "translation" of the tutorial above from C to python.

Using Cairo with Visual Studio A very basic guide for those who want to develop cairo applications using Visual Studio.

Using Cairo with SDL A very basic guide for those who want to develop cairo applications using SDL.

Using Cairo with OpenGL How to make use of cairo from within OpenGL-programs.

The Cairo graphics tutorial A 100+ pages tutorial in C programming language and GTK+ library, the largest tutorial on the Internet, ZetCode

Monochrome icon by Mike Massonnet, March 2010. A step-by-step tutorial that explains how to include a monochrome icon inside a GTK+ application. It starts with a minimal solution and evolves up to a more solid one with Cairo. All the examples are written in Vala language.

Presentations about cairo

Co-maintaining cairo: cool community, cool code by Behdad Esfahbod and Carl Worth, presented at GUADEC in July 2007.

An Insider's Guide to Cairo by Carl Worth, presented at the Desktop Developer's Conference in July 2005.

Cairo: Making Graphics Easy to Print by Carl Worth, presented at linux.conf.au in April 2005.

Xr: Cross-device Rendering for Vector Graphics by Carl Worth and Keith Packard, presented at the Linux Symposium in July 2003. This is from before Xr was renamed to cairo.

Please download one of the latest releases in order to get an API-stable version of cairo. You'll need both the cairo and pixman packages.

See In-Progress Development (below) for details on getting and building the latest pre-release source code if that's what you're looking for.

Binary Packages

GNU/Linux distributions

Many distributions including Debian, Fedora, and others regularly include recent versions of cairo. As more and more applications depend on cairo, you might find that the library is already installed. To get the header files installed as well may require asking for a -dev or -devel package as follows:

For Debian and Debian derivatives including Ubuntu:

Windows

Precompiled binaries for Windows platforms can be obtained in a variety of ways.

From Dominic Lachowicz:

Since GTK+ 2.8 and newer depends on Cairo, you can have Cairo installed on Win32 as a side-effect of installing GTK+. For example, see The Glade/GTK+ for Windows Toolkit.

From Daniel Keep (edited by Kalle Vahlman):

You probably want at least the zlib, cairo, and libpng run-time archives (you can search on those strings to find them in the page). That should be it. Just pop libcairo-2.dll, libpng13.dll and zlib1.dll into your working directory or system PATH, and away you go!

That gives you the base cairo functions, the PNG functions, and the Win32 functions.

Mac OS X

Using MacPorts, the port is called 'cairo', so you can just type:

And to upgrade to newer versions once installed:

If you use fink instead, the command to install cairo is:

In general, fink is more conservative about upgrading packages than MacPorts, so the MacPorts version will be closer to the bleeding edge, while the fink version may well be more stable.

If you want to stay on the absolute cutting-edge of what's happening with cairo, and you don't mind playing with software that is unstable and full of rough edges, then we have several things you might enjoy:

Snapshots

We may from time to time create a snapshot of the current state of cairo. These snapshots do not guarantee API stability as the code is still in an experimental state. Again, you'll want both cairo and pixman packages from that directory.

Browsing the latest code

The cairo library itself is maintained with the git version control system. You may browse the source online using the cgit interface.

Downloading the source with git

You may also use git to clone a local copy of the cairo library source code. The following git commands are provided for your cut-and-paste convenience.

followed by periodic updates in each resulting directory:

Once you have a clone this way, you can browse it locally with graphical tools such as gitk or gitview. You may also commit changes locally with "git commit -a". These local commits will be automatically merged with upstream changes when you next "git pull", and you can also generate patches from them for submitting to the cairo mailing list with "git format-patch origin". To compile the clone, you need to run ./autogen.sh initially and then follow the instructions in the file named INSTALL.

You may need some distribution-specific development packages to compile cairo. If your are using Debian or Ubuntu, you may find additional details for Debian-derived systems helpful.

Git under Linux/UNIX

Git on Windows

You can use Git on Windows either with msysgit or git inside Cygwin. Msysgit is the recommended way to go as the installation is much simpler and it provides a GUI. In all cases, make sure the drive you download the repository on is formatted NTFS, as Git will generate errors on FAT32.

See the msysgit project for the latest information about git for Windows. You'll find a .exe installer for git there, as well as pointers to the cygwin port of git as well. This is all you need to do.

Download and run the Cygwin Setup.exe from Cygwin's website. Walk through the initial dialog boxes until you reach the "Select Packages" page. Click the "View" button to display an alphabetical list of packages and select the 'git' package.

If you want to build using gcc, you will also need to select the following packages:

  • 'automake' ( anything >=1.7 )
  • 'gcc-core'
  • 'git' ( no need to click on this again if you did so above )
  • 'gtkdoc'
  • 'libtool'
  • 'pkg-config'

Whether you build with gcc or not:

Click 'Next' and Cygwin setup will download all you need. After downloading, go to the directory where Cygwin is installed, and run "cygwin.bat". This will open a command prompt. Mount an existing directory on your hard drive, cd to that directory, and then follow the "Downloading with git" instructions above.

If you want to build using Visual Studio and still want the latest source, you will need cygwin, but you will only need to select the 'git' package. See the Visual Studio page for more details.

Building in Visual Studio

You can create a Visual Studio solution and projects for each of these: pixman, cairo/src, cairo/boilerplate, cairo/test, cairo/perf. Check each project's properties, make them all makefile projects, and set the build command (NMake) as follows. This example applies to cairo/src in release configuration, residing in C:\Work\Cairo\src, with the Mozilla Build Tools installed in C:\mozilla-build:

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

Изображение, которое получено на экране, может быть также выведено в файл в различных форматах: pdf, ps, png, svg и других.

Библиотека Cairo используется в следующих популярных программах:

  • Фреймворк WebKit, который используется целым рядом браузеров: Google Chrome, Firefox, Safari, Яндекс.Браузер.
  • Графическая среда рабочего стола Gnome.
  • Набор офисных приложений OpenOffice.
  • Векторный графический редактор Inkscape.
  • Библиотека GTK+.

В сборке Си-экспресс библиотека Cairo уже встроена и готова к работе.

Что такое векторная графика?

Компьютерная графика может быть растровой или векторной. Растровая графика — графика, которая создается из отдельных точек (пикселей). Этот вид графики получается, например, в результате работы цифрового фотоаппарата или сканера.

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

При масштабировании качество растровой графики резко падает.

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

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

Поэтому для формирования изображений программисту намного удобнее и проще использовать векторную графику.

Графическая модель Cairo

Разработчики библиотеки Cairo исходили из предположения, что библиотека будет использоваться для различных трансформаций изображений. Отсюда они выбрали несколько сложную, но очень мощную модель формирования изображения.

Cairo использует следующую модель рисования:

Выбирается источник (source).
Он может быть закрашенной поверхностью, градиентом или битовым изображением. Источник может иметь альфа-канал прозрачности.

Рисуются векторные формы, которые называются маской (mask).

На окончательную поверхность (surface) попадают результаты прохождения источника сквозь маску.

Перед рисованием вы можете выбрать следующие источники:

  • cairo_set_source_rgb() — сплошной цвет
  • cairo_set_source_rgba() — прозрачный цвет
  • cairo_pattern_create_linear() — линейный
  • cairo_pattern_create_radial() — радиальный

Изображение

  • cairo_image_surface_create_from_png() — из файла
  • cairo_pop_group() — из сохраненного источника

Например, если мы хотим нарисовать синий круг, то нужно выполнить следующие команды:

1234 // Синий круг cairo_set_source_rgb( cr, 0, 0, 65535); // В качестве источника выбрали синий цвет cairo_arc (cr, 150, 125, 100, 0, 2*M_PI); // В качестве маски выбрали круг cairo_fill( cr ); // Перенесли на поверхность круг, заполненный цветом

Возможности библиотеки Cairo

Библиотека предоставляет полный набор работы с векторной графикой:

  • Рисование графических примитивов
  • Вывод текста
  • Отображение растровых рисунков
  • Линейный и радиальный градиент
  • Замыкание контуров
  • Трансформации фигур

Возможностей библиотеки достаточно для выполнения любых графических задач с векторной двумерной графикой.

Читайте также: