Use Cairo to implement cross-platform graphics

Source: Internet
Author: User
Tags cairo gtk

Source: http://www.ibm.com/developerworks/cn/linux/l-cairo? S_tact = 105agx52 & s_cmp = techcto

Vector Plotting library used to generate consistent output

Eli Dow, software engineer, IBM Linux test and Integration Center

 Introduction:Cairo's goal is to generate the same output on printers and screens in a cross-platform manner. It is becoming an important software in the Linux graphics field. Many software such as gnome, GTK +, and pango have used the 2D functions provided by gnome.

Advantages and uses of Cairo

Cairo is a free vector graphics software library that can draw multiple output formats. Cairo supports many platforms, including Linux, BSD, Microsoft Windows, and OSX (BEOs and os2 backend are also under development ). Linux graphics can be implemented through the X Window System, quartz, image buffer format, or OpenGL context. In addition, Cairo supports the generation of PostScript or PDF output to produce high-quality print results. Ideally, Cairo users can achieve very close output results on printers and screens.

This article will introduce you to Cairo and Its Significance to applications. The example in this article will generate a PDF, PS, PNG, SVG, and GTK window showing the IBM logo.

A major design goal of Cairo is to provide output as close as possible. This consistent output makes Cairo very suitable for GUI tool set programming and cross-platform application development. Using the same Drawing Library to print high-resolution screens and draw screen content has significant advantages.

In addition, Cairo tries to intelligently use underlying hardware and software support on each supported target platform. The combination of high-quality vector graphics and high performance makes Cairo an excellent UNIX graphics system.

Cairo is written in C, but it provides binding for most common languages. Selecting C language helps you create new bindings and provides high performance when you call C language. Special attention should be paid to Python binding, which supports rapid prototyping and lowers the threshold for learning Cairo plotting APIs.

Vector plot and bitmap plot

Cairo isVector drawing)Therefore, you must describe the ry of the graph rather than the pixels filled in the bitmap. In useBitmap drawing)According to the pre-determined layout, fill a series of pixels with pre-determined colors, and the image quality is proportional to the size of the bitmap.

When a bitmap image is enlarged or modified, the effect of the bitmap method becomes worse. The image is often blurred, like watching a back-cast TV or other large screen TV at close distance. At a certain distance, the image may look very clear, but after approaching, many discrete points will be seen. Because the data cannot define what should be between pre-defined pixels, the resolution is obviously lost when you zoom in.

The computer graphics system and architecture have appeared for a long time. Cairo's design draws on the experience of PostScript and PDF models. Cairo draws on the postscript and portable document format (pdf) methods because they all use mathematical statements to define images. Since the image is represented by a geometric method, you can calculate the geometric description within a certain range at any time to recreate the entire image (or part of the image ). The Geometric Properties of a graph are expressed as points, curves, and straight lines (these elements form vectors ).

Because you can re-calculate the mathematical description to re-draw an image or its components, there will be no resolution loss when you zoom in, zoom out, or transform the image. However, Vector Plotting has some limitations. For example, if a very high proportion of the vector image is scaled out of the range most people actually need, it may cause distortion. During amplification, some straight lines may look incorrect because errors are rounded in calculation. When narrowing down, some straight lines may be invisible or difficult to tell.

Cairo has another advantage in Vector Plotting: vector images are usually relatively small. This is because a large amount of information can be expressed using a rather simple mathematical expression. The advantage of Vector Plotting is that the plotting process is quite simple. The drawing library is responsible for converting points, lines, and related expressions into what you can see.

The expression used to describe the curve is calledBezr CurveOr path. The name is derived from the mathematician pierre. The besuppliers curve consists of at least two anchor points. there are one or more points between the anchor points calledHandle). Move the control point to change the shape of the curve. If you have used tools like Photoshop or gimp, you may be familiar with this curve. However, when using those tools, the final saved image format may be bitmap! The format of the file determines whether to retain the path information, or calculate it within a given range and save the calculation result in bitmap format.

When writing this article, the available Cairo bindings include C ++, Ruby, Perl, Java, and. Net/mono. These bindings are in different development statuses with different maturity levels. You can learn about the latest status on the Cairo project homepage (see the link in reference ). Currently, Python and C ++ bindings seem to be widely used in the open source code community.

As mentioned above, some graphic tool sets also provide Bindings for Cairo, which makes Cairo development easier. GTK + Versions later than 2.8 provide complete support for Cairo, and Cairo is used as the Basic Drawing System for later GTK versions. In addition, tools such as gnustep and fltk have begun to support Cairo to meet graphic presentation requirements.

If you plan to perform any cross-platform development and require lower-Layer Control Over Drawing operations and combinations, it is appropriate to use Cairo as the drawing API. If you need cross-platform functions, but do not need lower-layer drawing control, you can use some drawing libraries built on Cairo.

 

Back to Top

Why learning a new drawing model?

Frankly speaking, I think the current open source code solution is lacking in several aspects. The advantage of xprint is that it provides a unified display and printing API, but it is usually run as a separate server process, and its API is very bad. Libgnomeprint provides a separate print and display model, but the separation of the print and drawing APIs makes the screen and printer presentation different.

Cairo draws on a lot of experience from the previous Drawing Library and is designed to achieve a unified API from the very beginning.

 

Back to Top

Cairo presentation target

Cairo can present the following output formats:

  • X Window System (if possible, the Render Extension will be used)
  • OpenGL (using glitz backend)
  • In-memory images (pixbuffs, etc)
  • Postscript (for printing)
  • PDF (Portable Document Format) File
  • SVG (Scalable Vector Graphics) Format

However, not all rendering targets have the same effect. Although Cairo strives to produce the same output on various backend servers, each backend has its own advantages. For example, the backend of the PDF uses vector computing (generating images only when necessary), while the backend of the postscript actually generates a large image for each page.

The rendering model in Cairo is affected by many original technologies. Cairo adopts the path, stroke, and fill concepts in postscript, and implements the Porter-Duff Image Combination Technology in the implementation of PDF and modern X servers. In addition, Cairo provides cutting, masking, gradient, and other supplementary features.

 

Back to Top

Actual Application of Cairo

Cairo has been used in many influential open source projects, and Cairo has become an important software in the Linux graphics field. Important projects that have adopted Cairo include:

  • GTK +, a popular cross-platform Graphics Tool Set
  • Pango is a free software library for text layout and presentation. It is mainly used for internationalization.
  • Gnome, a free desktop environment
  • Mozilla is a cross-platform Web browser infrastructure built on Firefox.
  • OpenOffice.org, a free office suite that can rival Microsoft Office
 

Back to Top

Use Cairo for conceptual plotting

When drawing with Cairo, the simplest operation is like when painting manually: select the drawing medium, select the paint brush, select the color, consider the layout of the line, and then draw the actual. The Cairo document describes Cairo operations by analogy with the painter's painting process. The following describes how to use this method.

For painters, the easiest thing is to select a Blank Drawing medium. In the real world, artists can paint on paper, canvas, or even on walls. In Cairo, you must also select a Blank Drawing medium. When drawing with Cairo, you need to set a Cairo context, which is the main object. In this context, you can select the target appearance, such as a postscript file, PDF file, or screen image. In this way, we can select what we want to plot.

Now consider the painter's next task: select a paint brush. Painters often spend a considerable amount of time selecting the appropriate shape and size of the paint brush. In Cairo, there is also the concept of the brush shape, which is expressed by the stroke width. Different stroke widths produce lines of different thicknesses.

Next, Cairo users need to express drawing operations with precise coordinates, which is different from the Painting Process in the real world. The artist only needs to place the paint brush in the approximate position on the paper, but the computer must know the X and Y coordinates of the drawing.

After setting the paint brush and starting the drawing, you need to imagine the shape of the stroke. A simple graph may consist of straight lines, but like a real painter, you can draw curves and arcs.

Finally, the position at which the stroke is terminated must be defined. Similarly, this position must be specified by a pair of (x, y) coordinates.

In addition, you can also color the drawn object. In Cairo terminology, this is calledFill (fill). For each operation described above, Cairo has a corresponding Simple API implementation. Some APIs will be introduced later.

These basic operations can help you build complex graphics. You can even use Cairo to execute the work that painters cannot do easily, such as enlarging or transforming existing images, or moving the images to other places on the virtual paper.

Gimp or photoshop can also perform many of these operations, but Cairo is different: Cairo is a programmatic plotting method. Gimp and photoshop "behind the scenes" use tools like Cairo for plotting. When drawing with these tools, you can use the mouse to automatically set the coordinates and tool types (such as boxes), and select the width of the paint brush and stroke through the GUI environment. As shown in the sample code (see download), Cairo requires explicit interaction. For example, "Draw an arc with stroke width 1 with a radius of 10 and center at Z ".

 

Back to Top

Correct Cairo terminology

Use the correct terminology when discussing any technology. Cairo API terms fall into three categories: Core Drawing terms, appearance terms, and font-related terms (for more details, see references ).

First, Cairo has a drawing context, which is equivalent to the painter's canvas. The context is of the cairo_t type. to render a graph, there must be a context. A common operation in the drawing context is to draw betiller graphics, straight lines, and curves. Cairo stands for a series of curves and related data. The term isPath). You can draw these paths and set the stroke width or fill.

Use a very simple API to convert coordinates to paths. This API makes sense because it frees us from considering the complex conversion matrices discussed in linear algebra or graphics textbooks. You can perform any conversion on the Cairo plot operation, including cutting, scaling, or rotating a graph or part of it. Draw each path by specifying a vertex. Cairo performs operations by connecting points. An example is provided later.

Next, we will discuss the appearance types of Cairo. There are several types of Cairo appearance, which correspond to one output target respectively. CairoSurface)Is the position where the drawing is executed. Specifically, there are appearances for images (memory buffers), glitz appearances for Open GL, PDF and postscript appearances for document presentation, and xlib and Win32 appearances for direct drawing execution. These external types are derived from the external base type cairo_surface_t.

In Cairo,Pattern)Is a readable content that is used as the source or mask for drawing operations. The Mode in Cairo can be the entity mode, the external mode, or even the progressive mode.

So far, we have only talked about the stroke path. However, stroke paths can only generate less interesting line charts. In fact, simple line strokes are only one of the five basic drawing operations in Cairo. These five operations are:

  • Cairo_stroke
  • Cairo_fill
  • Cairo_show_text/cairo_show_glyphs
  • Cairo_paint
  • Cairo_mask

Although simple line drawing is very convenient, they are not expressive enough to express complex graphics such as fonts. Cairo provides a base class cairo_font_face_t for the font. Cairo supports zooming fonts that contain cache standards for the given font size. In addition, you can use various font options to control how to display a given font. When Cairo is used, the commonly used fonts on UNIX are FreeType fonts, and Win32 fonts are used on Windows platforms.

 

Back to Top

Cairo Sample Application

I wrote a piece of Cairo code for drawing the IBM logo. You can download this code from the download section below. Running it should produce the following output:

Figure 1. IBM logo generated with Cairo
 

Note thatcairo_stroke (cr)Line. This line appears after the letter is drawn, but before the sign is added. Cairo does not draw anything if no strokes are set. Forgetting to set strokes is a common mistake for beginners.

 

Back to Top

Cairo's development process

The Cairo version uses a rule similar to the Linux kernel-that is, the odd version is an experimental development version and is not suitable for use in the production environment. The even version is a stable version: the original version 1.0 focuses on smoothly providing APIs to users and generating high-quality output. 1.2 The API has improved several backend systems with incomplete development. The current 1.4 series focuses on optimization and addition of new features.

Cairo developers provide some excellent sample code snippets to demonstrate the functions of Cairo APIs (see the link in the references section ). So you don't have to wait for the next version of Cairo. Download and try the current version now!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.