- cairoSurface
- class cairoSurface
- copy_page li>
- create_similarcontent width height
- finish
- flush
- get_content
- get_device_offset
- get_fallback_resolution
- get_font_options
- mark_dirty
- mark_dirty_rectanglex y width height
- set_device_offsetx_offset y_offset
- set_fallback_resolutionx_pixels_per_inch y_pixels_per_inch
- show_page
- write_to_pngfobj
li>
- class ImageSurfaceSurface
- class cairoImageSurfaceformat width height
- classmethod create_for_datadata format width height stride< /li>
- classmethod create_from_pngfobj
- static format_stride_for_widthformat width
- get_data
- get_format
- get_height
- get_stride
- get_width
- class PDFSurfaceSurface
- class cairoPDFSurfacefobj width_in_points height_in_points
- set_size
li>
- class PSSurfaceSurface
- class cairoPSSurfacefobj width_in_points height_in_points
- dsc_begin_page_setup
- dsc_begin_setup< /li>
- dsc_commentcomment
- get_eps
- static ps_level_to_stringlevel
- restrict_to_levellevel
- set_epseps
- set_sizewidth_in_points height_in_points< /li>
- class SVGSurfaceSurface
- class cairoSVGSurfacefobj width_in_points height_in_points
- get_versions
- restrict_to_version
- version_to_string
- class Win32SurfaceSurface
- class cairoW in32Surfacehdc
- class Win32PrintingSurfaceSurface
- class cairoWin32PrintingSurfacehdc
- class XCBSurfaceSurface
- class cairoXCBSurface
- set_sizewidth height
- class XlibSurfaceSurface
- class cairoXlibSurface
- get_depth
- get_height
- get_width
- class cairoSurface
- Example
< p>
The examples in this article need to use the cairo.Surface class
cairo.Surface
cairo.Surface is the abstract type representing all different drawing targets that cairo can render to. The actual drawings are performed using a Context.
A cairo.Surface is created by using backend-specific constructors of the form cairo.Surface().
class cairo.Surface
Surface is the abstract base class from which all the other surfac e classes derive. It cannot be instantiated directly.
copy_page()
Emits the current page for backends that support multiple pages, but doesn’t clear it, so that the contents of the current page will be retained for the next page. Use show_page() if you want to get an empty page after the emission.
Context.copy_page() is a convenience function for this .
New in version 1.6.
create_similar(content, width, height)
Parameters:
content – the CONTENT for the new surface
width (int) – width of the new surface, (in device-space units)
height – height of the new surface (in device-space units)
Returns:
a newly allocated Surface.
Create a Surface that is as compatible as possible with the existing surface. For example the new surface will have the same fallback resolution and FontOptions. Generally, the new surface will also use the same backe nd, unless that is not possible for some reason.
Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)
finish( )
This method finishes the Surface and drops all references to external resources. For example, for the Xlib backend it means that cairo will no longer access the drawable, which can be freed. After calling finish() the only valid operations on a Surface are flushing and finishing it. Further drawing to the surface will not affect the surface but will instead trigger a cairo.Error exception.
flush()
Do any pending drawing for the Surface and also restore any temporary modification’s cairo has made to the Surface’s state. This method must be called before switching from drawing on the Surface with cairo to drawing on it directly with native APIs. If the Surface doesn’t support direct access, then this function does nothing.
get_content()
New in version 1.2.
get_device_offset()
Returns: (x_offset, y_offset) a tuple of float
x_offset: the offset in the X direction, in device units
y_offset: the offset in the Y direction, in device units
This method returns the previous device offset set by set_device_offset().
New in version 1.2.
get_fallback_resolution()
Returns: (x_pixels_per_inch, y_pixels_per_inch) a tuple of float
x_pixels_per_inch: horizontal pixels per inch
y_pixels_per_inch: vertical pixels per inch resolution
This method returns the previous fallback set by set_fallback_resolution(), or default fallback resolution if never set.
New in version 1.8.
get_font_options()
Returns: a FontOptions pre> Retrieves the default font rendering options for the Surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with ScaledFont.
mark_dirty()
Tells cairo that drawing has been done to Surface using means other than cairo, and that cairo should reread any cached areas. Note that you must call flush() before doing such drawing.
mark_dirty_rectangle(x, y, width, height)
Parameters:
x (int) – X coordinate of dirty rectangle
y (int) – Y coordinate of dirty rectangle
width (int) – width of dirty rectangle
height (int) – height of dirty rectangle
Like mark_dirty(), but drawing has been done only to the specified rectangle, so that cairo can retain cached contents for other parts of the surface.
Any cached clip set on theSurface will be reset by this function, to make sure that future cairo calls have the clip set that they expect.
set_device_offset(x_offset, y_offset)
Parameters:
x_offset (float) – the offset in the X direction, in device units
y_offset (float) – the offset in the Y direction, in device units
Sets an offset that is added to the device coordinates determined by the CTM when drawing to Surface. One use case for this function is when we want to create a Surface that redirects drawing for a portion of an onscreen surface to an offscreen surface in a way that is completely invisible to the user of the cairo API. Setting a transformation via Context.translate() isn't sufficient to do this, since functions like Context.device_to_user() will expose the hidden offset.
Note that the offset affects drawing to the surface as well as using the surface in a source pattern.
set_fallback_resolution(x_pixels_per_inch, y_pixels_per_inch)
Parameters:
x_pixels_per_inch (float) – horizontal setting for pixels per inch
y_pixels_per_inch (float) – vertical setting for pixels per inch
Set the horizontal and vertical resolution for image fallbacks.
When certain operations aren't supported natively by a backend, cairo will fallback by rendering operations to an image and then overlaying that image onto the output. For backends that are natively vector-oriented, this function can be used to set the resolution used for these image fallbacks, (larger values will result in more detailed images, but also larger file sizes).
< p>Some examples of natively vector-oriented backends are the ps, pdf, and svg backends.
For backends that are natively raster-oriented, image fallbacks are still possible, but they are always performed at the native device resolution. So this function has no effect on t hose backends.
Note: The fallback resolution only takes effect at the time of completing a page (with Context.show_page() or Context.copy_page()) so there is currently no way to have more than one fallback resolution in effect on a single page.
The default fallback resoultion is 300 pixels per inch in both dimensions.
New in version 1.2.
show_page()
Emits and clears the current page for backends that support multiple pages. Use copy_page() if you don't want to clear the page.
There is a convenience function for this that takes a Context.show_page().
New in version 1.6.
write_to_png(fobj)
Parameters :
fobj (str, file or file-like object) – the file to write to
Raises:
MemoryError if memory could not be allocated for the operation
IOError if an I/O error occurs while attempting to write the file
Writes the contents of Surface to fobj as a PNG image.
class ImageSurface(Surface)
A cairo.ImageSurface provides the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in FORMAT attributes.
class cairo.ImageSurface(format, width, height)
Parameters:
format – FORMAT of pixels in the surface to create
width – width of the surface, in pixels
height – height of the surface, in pixels
Returns:
a new ImageSurface
Raises:
MemoryError in case of no memory
Creates an ImageSurface of the specified format and dimensions. Initially the surface contents are all 0. (Specifically, within each pixel, each color or alpha channel belonging to format will be 0. The contents of bits within a pixel, but not belonging to the given format are undefined).
classmethod create_for_data(data, format, width, height[, stride])
Not yet available in Python 3
classmethod create_from_png( fobj)
Parameters: fobj – a filename, file, or file-like object of the PNG to load.
Returns: a new ImageSurface initialized the contents to the given PNG file.
static format_stride_for_width(format, width)
Parameters:
format – a cairo FORMAT value
width – the desired width of an ImageSurface to be created.
Returns:
the appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large.
Return type: < br /> int
This method provides a stride value that will respect all alignment requirements of the accelerated image-rendering code within cairo. Typical usage will be of the form:
str ide = cairo.ImageSurface.format_stride_for_width (format, width)surface = cairo.ImageSurface.create_for_data (data, format, width, height, stride)
New in version 1.6. p>
get_data()
Not yet available in Python 3
get_format()
Returns: the FORMAT of the ImageSurface.
New in version 1.2.
get_height()
Returns: the height of the ImageSurface in pixels.
get_stride()
Returns: the stride of the ImageSurface in bytes. The stride is the distance in bytes from the beginning of one row of the image data to the beginning of the next row.
get_width()
Returns: the width of the ImageSurface in pixels.
class PDFSurface(Surface)
The PDF Surface is used to render cairo graphics to Adobe PDF files and is a multi-page vector surface backend.
class cairo.PDFSurface(fobj, width_in_points, height_in_points)
Parameters:
fobj (None, str, file or file-like object) – a filename or writable file object. None may be used to specify no output. This will generate a PDFSurface that may be queried and used as a source, without generating a temporary file.
width_in_points (float) – width of the surface, in points (1 point == 1/72.0 inch)
height_in_points (float) – height of the surface, in points (1 point == 1/72.0 inch)
Returns:
a new PDFSurface of the specified size in points to be written to fobj.
Raises:
MemoryError in case of no memory
New in version 1.2.
set_size()
Parameters:
width_in_points (float) – new surface width, in points (1 point == 1/72 .0 inch)
height_in_points (float) – new surface height, in points (1 point == 1/72.0 inch)
Changes the size of a PDFSurface for the current (and subsequent) pages .
This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface or immediately after completing a page with either Context.show_page() or Context.copy_page().
New in version 1.2.
class PSSurface(Surface)
The PSSurface is used to render cairo graphics to Adobe PostScript files and is a multi-page vector surface backend.
class cairo.PSSurface(fobj, width_in_points, height_in_points )
Parameters:
fobj (None, str, file or file-like object) – a filename or writable file object. None may be used to specify no output. This will generate a P SSurface that may be queried and used as a source, without generating a temporary file.
width_in_points (float) – width of the surface, in points (1 point == 1/72.0 inch)
height_in_points (float ) – Height of the surface, in points (1 point == 1/72.0 inch)
Returns:
a new PDFSurface of the specified size in points to be written to fobj.
Raises:
MemoryError in case of no memory
Note that the size of individual pages of the PostScript output can vary. See set_size().
dsc_begin_page_setup()< /h3>
This method indicates that subsequent calls to dsc_comment() should direct comments to the PageSetup section of the PostScript output.
This method call is only needed for the first page of a surface. It should be called after any call to dsc_begin_setup() and before any drawing is performed to the surface.
See dsc_comment() for more details.
New in version 1.2.
ds c_begin_setup()
This function indicates that subsequent calls to dsc_comment() should direct comments to the Setup section of the PostScript output.
This function should be called at most once per surface, and must be called before any call to dsc_begin_page_setup() and before any drawing is performed to the surface.
See dsc_comment() for more details.
New in version 1.2.
p>
dsc_comment(comment)
Parameters: comment (str) – a comment string to be emitted into the PostScript output
Emit a comment into the PostScript output for the given surface.
The comment is expected to conform to the PostScript Language Document Structuring Conventions (DSC). Please see that manual for details on the available comments and their meanings. In particular, the% %IncludeFeature comment allows a device-independent means of controlling printer device features. So the PostScript Printer Description Files Specification will als o be a useful reference.
The comment string must begin with a percent character (%) and the total length of the string (including any initial percent characters) must not exceed 255 characters. Violating either of these conditions will place PSSurface into an error state. But beyond these two conditions, this function will not enforce conformance of the comment with any particular specification.
The comment string should not have a trailing newline.
< p>The DSC specifies different sections in which particular comments can appear. This function provides for comments to be emitted within three sections: the header, the Setup section, and the PageSetup section. Comments appearing in the first two sections apply to the entire document while comments in the BeginPageSetup section apply only to a single page.
For comments to appear in the header section, this function should be called after the surface is created, but before a call to dsc_begin_setup().< /p>
For com ments to appear in the Setup section, this function should be called after a call to dsc_begin_setup() but before a call to dsc_begin_page_setup().
For comments to appear in the PageSetup section, this function should be called after a call to dsc_begin_page_setup().
Note that it is only necessary to call dsc_begin_page_setup() for the first page of any surface. After a call to Context.show_page() or Context.copy_page() comments are unambiguously directed to the PageSetup section of the current page. But it doesn't hurt to call this function at the beginning of every page as that consistency may make the calling code simpler.
As a final note, cairo automatically generates several comments on its own. As such, applications must not manually generate any of the following comments:
Header section: %!PS-Adobe-3.0, %Creator, %CreationDate, %Pages, %BoundingBox, %DocumentData, %LanguageLevel, %EndComments.
Setup section: %BeginSetup, %EndSetup
PageSe tup section: %BeginPageSetup, %PageBoundingBox, %EndPageSetup.
Other sections: %BeginProlog, %EndProlog, %Page, %Trailer, %EOF
Here is an example sequence showing how this function might be used:
surface = PSSurface (filename, width, height)...surface.dsc_comment (surface , "%%Title: My excellent document")surface.dsc_comment (surface, "%%Copyright: Copyright (C) 2006 Cairo Lover")...surface.dsc_begin_setup (surface)surface.dsc_comment (surface, "% %IncludeFeature: *MediaColor White")...surface.dsc_begin_page_setup (surface)surface.dsc_comment (surface, "%%IncludeFeature: *PageSize A3")surface.dsc_comment (surface, "%%IncludeFeature: *InputSlot LargeCapacity")surface.dsc_comment (sur face, "%%IncludeFeature: *MediaType Glossy")surface.dsc_comment (surface, "%%IncludeFeature: *MediaColor Blue ")... draw to first page here ..ctx.show_page (cr)...< /span>surface.dsc_comment (surface, "%%IncludeFeature: PageSize A5");...
New in version 1.2.
get_eps()
Returns: True iff the PSSurface will output Encapsulated PostScript.
< p>New in version 1.6.
static ps_level_to_string(level)
Parameters: level – a PS_LEVEL
Returns: the string associated to given level.
Return type: str
Raises: cairo.Error if level isn't valid.
Get the string representation of the given level. See ps_get_levels() for a way to get the list of valid level ids.
New in version 1.6.
< h3 id="restricttolevellevel">restrict_to_level(level)
Parameters: level – a PS_LEVEL
Restricts the generated PostSript file to level. See ps_get_levels() for a list of available level values that can be used here.
This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.
p>
New in version 1.6.
set_eps(eps)
Parameters: eps (bool) – True to output EPS format PostScript
If eps is True, the PostScript surface will output Encapsulated PostScript.
This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface. An Encapsulated PostScript file should never contain more than one page.
New in version 1.6.
set_size(width_in_points, height_in_points)
Parameters:
width_in_points (float) – new surface width, in points (1 point == 1/72.0 inch)
height_in_points (float ) – New surface height, in points (1 point == 1/72.0 inch)
Changes the size of a PostScript surface for the current (and subsequent) pages.
This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface or immediately after completing a page with either Context.show_page() or Context.copy_page( ).
New in version 1.2.
class SVGSurface(Surface)
The SVGSurface is used to render cairo graphics to SVG files and is a multi-page vector surface backend
class cairo.SVGSurface(fobj, width_in_points, height_in_points)
Paramet ers:
fobj (None, str, file or file-like object) – a filename or writable file object. None may be used to specify no output. This will generate a SVGSurface that may be queried and used as a source , without generating a temporary file.
width_in_points (float) – width of the surface, in points (1 point == 1/72.0 inch)
height_in_points (float) – height of the surface, in points ( 1 point == 1/72.0 inch)
Returns:
a new SVGSurface of the specified size in points to be written to fobj.
Raises:
MemoryError in case of no memory
get_versions()
Not implemented in pycairo (yet)
restrict_to_version()
Not implemented in pycairo (yet)
version_to_string()
Not implemented in pycairo (yet)
class Win32Surface(Surface)
The Microsoft Windows surface is used to render cairo graphics to Microso ft Windows windows, bitmaps, and printing device contexts.
class cairo.Win32Surface(hdc)
Parameters: hdc (int) – the DC to create a surface for
Returns: the newly created surface
Creates a cairo surface that targets the given DC. The DC will be queried for its initial clip extents, and this will be used as the size of the cairo surface. The resulting surface will always be of format cairo.FORMAT_RGB24, see FORMAT attributes.
class Win32PrintingSurface(Surface)
The Win32PrintingSurface is a multi-page vector surface type.
class cairo.Win32PrintingSurface(hdc)
Parameters: hdc (int) – the DC to create a surface for< br />Returns: the newly created surface
Creates a cairo surface that targets the given DC. The DC will be queried for its initial clip extents, and this will be used as the size of the cai ro surface. The DC should be a printing DC; antialiasing will be ignored, and GDI will be used as much as possible to draw to the surface.
The returned surface will be wrapped using the paginated surface to provide correct complex rendering behaviour; cairo.Surface.show_page() and associated methods must be used for correct output.
class XCBSurface(Surface)
The XCB surface is used to render cairo graphics to X Window System windows and pixmaps using the XCB library.
Note that the XCB surface automatically takes advantage of the X render extension if it is available.
class cairo.XCBSurface
Parameters:
connection – an XCB connection
drawable – a X drawable
visualtype – a X visualtype
width – The surface width
height – The surface height
Creates a cairo surface that targets the given drawable (pixmap or window).
Note This met hods works using xpyb.
set_size(width, height)
Parameters:
width – The width of the surface
height – The height of the surface
Informs cairo of the new size of the X Drawable underlying the surface. For a surface created for a Window (rather than a Pixmap), this function must be called each time the size of the window changes. (For a subwindow, you are normally resizing the window yourself, but for a toplevel window, it is necessary to listen for ConfigureNotify events.)
A Pixmap can never change size, so it is never necessary to call this function on a surface created for a Pixmap.
class XlibSurface(Surface)
The XLib surface is used to render cairo graphics to X Window System windows and pixmaps using the XLib library.
Note that the XLib surface automatically takes advantage of X render extension if it is available.
clas s cairo.XlibSurface
Note XlibSurface cannot be instantiated directly because Python interaction with Xlib would require open source Python bindings to Xlib which provided a C API. However, an XlibSurface instance can be returned from a function call when using pygtk http://www.pygtk.org/.
get_depth()
Returns: the number of bits used to represent each pixel value.
New in version 1.2.
get_height()
Returns: the height of the X Drawable underlying the surface in pixels.
New in version 1.2.
get_width()
Returns: the width of the X Drawable underlying the surface in pixels.
New in version 1.2.
example
Code:
#!/usr/b in/env python3# Created by xiaosanyu at 16/7/6# section 150TITLE = "Reflection"DESCRIPTION = """ In the next example we show a reflected image. This beautiful effect makes an illusion as if the image was reflected in water """import gigi.require_version("Gtk" , "3.0")from gi.repository import Gtkimport cairoimport sysimport osclass PyApp(Gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Reflection ") self.resize(330, 450) self.connect("destroy", Gtk.main_quit) darea = Gtk.DrawingArea() darea.connect("draw", self.draw ) self.add(darea) try: self.surface = cairo.ImageSurface.create_from_png( os.path.join(os.path.dirname(__file__), "../data/lft.png")) except Exception as e: print(e) sys.exit(1) self.imageWidth = self.surface.get_width() self.imageHeight = self.surface. get_height() self.gap = 30 self.border = 20 self.show_all() def draw(self, drawingArea, cr): w = drawingArea.get_allocated_width () h = drawingArea.get_allocated_height() lg = cairo.LinearGradient(w / 2, 0, w / 2, h * 3) lg.add_color_stop_rgba(0 , 0.6, 0.6, 0.6 span>, 1) lg.add_color_stop_rgba(h, 0.2, 0.2, 0.2, 1) cr.set_source(lg) cr.paint() cr.set_sour ce_surface(self.surface, self.border, self.border) cr.paint() alpha = 0.8 step = 1.0 / self.imageHeight cr.translate(0, 2 * self.imageHeight + self.gap) cr.scale(1, -1) i = 0 while i < self.imageHeight: cr.rectangle(self.border, self.imageHeight - i, self.imageWidth, 1) i += 1 cr.save() cr.clip() cr.set_source_surface(self.surface, self.border, self.border) alpha -= step cr.paint_with_alpha(alpha) cr.restore()def main(): PyApp() Gtk.main()if __name__ == "__main__": main()
代码下载地址:http://download.csdn.net/detail/a87b01c14/9594728
- cairoSurface
- class cairoSurface
- copy_page
- create_similarcontent width height
- finish
- flush
- get_content
- get_device_offset
- get_fallback_resolution
- get_font_options
- mark_dirty
- mark_dirty_rectanglex y width height
- set_device_offsetx_offset y_offset
- set_fallback_resolutionx_pixels_per_inch y_pixels_per_inch
- show_page
- write_to_pngfobj
- class ImageSurfaceSurface
- class cairoImageSurfaceformat width height
- classmethod create_for_d atadata format width height stride
- classmethod create_from_pngfobj
- static format_stride_for_widthformat width
- get_data
- get_format
- get_height
- get_stride
- get_width
- class PDFSurfaceSurface
- class cairoPDFSurfacefobj width_in_points height_in_points
- set_size
- class PSSurfaceSurface
- class cairoPSSurfacefobj width_in_points height_in_points
- dsc_begin_page_setup
- dsc_begin_setup
- dsc_commentcomment
- get_eps
- static ps_level_to_stringlevel
- restrict_to_levellevel
- set_epseps
- set_sizewidth_in_points height_in_points
- class SVGSurfaceSurface
- class cairoSVGSurfacefobj width_in_points height_in_points
- get_ver sions
- restrict_to_version
- version_to_string
- class Win32SurfaceSurface
- class cairoWin32Surfacehdc
- class Win32PrintingSurfaceSurface
- class cairoWin32PrintingSurfacehdc
- class XCBSurfaceSurface
- class cairoXCBSurface
- set_sizewidth height
- class XlibSurfaceSurface
- class cairoXlibSurface
- get_depth
- get_height
- get_width
- 例子
- cairoSurface
- class cairoSurface
- copy_page
- create_similarcontent width height
- finish
- flush
- get_content
- get_device_offset
- get_fallback_resolution
- get_font_options
- mark_dirty li>
- mark_dirty_rectanglex y width height
- set_device_offsetx_offset y_offset
- set_fallback_resolutionx_pixels_per_inch y_pixels_per_inch
- show_page
- write_to_pngfobj
- class ImageSurfaceSurface
- class cairoImageSurfaceformat width height
- classmethod create_for_datadata format width height stride
- classmethod create_from_pngfobj
- static format_stride_for_widthformat width
- get_data
- get_format
- get_height
- get_stride
- get_width
- class PDFSurfaceSurface
- class cairoPDFSurfacefobj width_in_points height_in_points
- set_size
- class PSSurfaceSurface
- class cairoPSSurfacefobj width_in_points height_in_points
- dsc_begin_page_setup
- dsc_begin_setup
- ds c_commentcomment
- get_eps
- static ps_level_to_stringlevel
- restrict_to_levellevel
- set_epseps
- set_sizewidth_in_points height_in_points
- class SVGSurfaceSurface
- class cairoSVGSurfacefobj width_in_points height_in_points
- get_versions
- restrict_to_version
- version_to_string
- class Win32SurfaceSurface
- class cairoWin32Surfacehdc
- class Win32PrintingSurfaceSurface
- class cairoWin32PrintingSurfacehdc
- class XCBSurfaceSurface
- class cairoXCBSurface
- set_sizewidth height
- class XlibSurfaceSurface
- class cairoXlibSurface
- get_depth
- get_height
- get_width
- class cairoSurface
- 例子