This piece of code allows you to convert a Cairo surface to a PyGame surface. It also includes a small example on how to make SVG loading work. It works with Python 2.5+ and requires relatively recent versions of pygame, pycairo and NumPy to work. For the SVG example to work, you must also have rsvg installed.
#!/usr/bin/env python
# Copyleft 2010 Niels Serup, WTFPL 2.0. Free software.
### Imports ###
import math
import pygame
import cairo
import numpy
import Image
### Constants ###
width, height = 640, 480
### Functions ###
def draw(ctx):
ctx.set_line_width(15)
ctx.arc(320, 240, 200, 0, 2 * math.pi)
# r g b a
ctx.set_source_rgba(0.6, 0, 0.4, 1)
ctx.fill_preserve()
# r g b a
ctx.set_source_rgba(0, 0.84, 0.2, 0.5)
ctx.stroke()
def bgra_surf_to_rgba_string(cairo_surface):
# We use PIL to do this
img = Image.frombuffer(
'RGBA', (cairo_surface.get_width(),
cairo_surface.get_height()),
cairo_surface.get_data(), 'raw', 'BGRA', 0, 1)
return img.tostring('raw', 'RGBA', 0, 1)
### Body ###
# Init PyGame
pygame.display.init()
screen = pygame.display.set_mode((width, height), 0, 32)
# Create raw surface data (could also be done with something else than
# NumPy)
data = numpy.empty(width * height * 4, dtype=numpy.int8)
# Create Cairo surface
cairo_surface = cairo.ImageSurface.create_for_data(
data, cairo.FORMAT_ARGB32, width, height, width * 4)
# Draw with Cairo on the surface
ctx = cairo.Context(cairo_surface)
draw(ctx)
##### SVG LOADING EXAMPLE #####
# Using rsvg it is possible to render an SVG file onto a Cairo
# surface. Uncomment the following lines to make it work.
#import rsvg # This will probably not work in Windows. As far as I
# know, only GNU/Linux distibutions package this Python
# module. Nevertheless, it should be easy to create a small wrapper;
# see http://www.cairographics.org/cairo_rsvg_and_python_in_windows/
# Load the file
#svg_graphics = rsvg.Handle('path/to/file.svg')
# Render the graphics onto your Cairo context
#svg_graphics.render_cairo(ctx)
# To get the SVG file's dimensions before you create a Cairo surface,
# use the following function:
#print svg_graphics.get_dimension_data()
###############################
# On little-endian machines (and perhaps big-endian, who knows?),
# Cairo's ARGB format becomes a BGRA format. PyGame does not accept
# BGRA, but it does accept RGBA, which is why we have to convert the
# surface data. You can check what endian-type you have by printing
# out sys.byteorder
data_string = bgra_surf_to_rgba_string(cairo_surface)
# Create PyGame surface
pygame_surface = pygame.image.frombuffer(
data_string, (width, height), 'RGBA')
# Show PyGame surface
screen.blit(pygame_surface, (0,0))
pygame.display.flip()
clock = pygame.time.Clock()
while not pygame.QUIT in [e.type for e in pygame.event.get()]:
clock.tick(30)
This method allows Cairo to use the same block of memory for the surface
as pygame does. This is most likely the fastest method of the ones listed
here, since it doesn't use an extra buffer.
(Tested on Python 2.6.4, pycairo 1.8.6, Cairo 1.8.8, pygame 1.8.1, numpy 1.3.0.)
(note: does not work, if numeric is installed)
#!/usr/bin/env python
import cairo
import pygame
import math
size = 400, 400
# Initialize pygame with 32-bit colors. This setting stores the pixels
# in the format 0x00rrggbb.
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
# Get a reference to the memory block storing the pixel data.
pixels = pygame.surfarray.pixels2d(screen)
# Set up a Cairo surface using the same memory block and the same pixel
# format (Cairo's RGB24 format means that the pixels are stored as
# 0x00rrggbb; i.e. only 24 bits are used and the upper 16 are 0).
cairo_surface = cairo.ImageSurface.create_for_data(
pixels.data, cairo.FORMAT_RGB24, size[0], size[1])
# Draw a white circle to the screen using pygame.
radius = int(min(size)/2*0.7)
pos = [int(a/2) for a in size]
pygame.draw.circle(screen, (255,255,255), pos, radius)
# Draw a smaller black circle to the screen using Cairo.
context = cairo.Context(cairo_surface)
context.set_source_rgb(0, 0, 0)
context.arc(size[0]/2, size[1]/2, min(size)/2*0.5, 0, 2*math.pi)
context.fill()
# Flip the changes into view.
pygame.display.flip()
# Wait for the user to quit.
while pygame.QUIT not in [e.type for e in pygame.event.get()]:
pass
Following works with Python 2.5, pycairo-1.4.12-1, pygame 1.8.0:
Found at: http://www.pjblog.net/index.php?2006/06/23/144-using-pycairo-with-pygame-surface
Written by Pierre-Jean Coudert
#!/usr/bin/env python
import cairo
import pygame
import array
import math
import sys
def draw(surface):
x,y, radius = (250,250, 200)
ctx = cairo.Context(surface)
ctx.set_line_width(15)
ctx.arc(x, y, radius, 0, 2.0 * math.pi)
ctx.set_source_rgb(0.8, 0.8, 0.8)
ctx.fill_preserve()
ctx.set_source_rgb(1, 1, 1)
ctx.stroke()
def input(events):
for event in events:
if event.type == pygame.QUIT:
sys.exit(0)
else:
print event
#Create Cairo Surface
Width, Height = 512, 512
data = array.array('c', chr(0) * Width * Height * 4)
stride = Width * 4
surface = cairo.ImageSurface.create_for_data (data, cairo.FORMAT_ARGB32,Width, Height, stride)
#init PyGame
pygame.init()
window = pygame.display.set_mode( (Width,Height) )
screen = pygame.display.get_surface()
#Draw with Cairo
draw(surface)
#Create PyGame surface from Cairo Surface
image = pygame.image.frombuffer(data.tostring(),(Width,Height),"ARGB",)
#Tranfer to Screen
screen.blit(image, (0,0))
pygame.display.flip()
while True:
input(pygame.event.get())
Note: this does *not* work with Python 2.5: http://thread.gmane.org/gmane.linux.debian.devel.bugs.general/437547/focus=14467
#!/usr/bin/env python
import cairo
w, h = 128, 128
# Setup Cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
ctx = cairo.Context(surface)
# Set thickness of brush
ctx.set_line_width(15)
# Draw out the triangle using absolute coordinates
ctx.move_to(w/2, h/3)
ctx.line_to(2*w/3, 2*h/3)
ctx.rel_line_to(-1*w/3, 0)
ctx.close_path()
# Apply the ink
ctx.stroke()
# Output a PNG file
surface.write_to_png("triangle.png")
# Alias the image as a numpy array
import numpy
# This needs better than pycairo-1.2.2, eg. pycairo CVS:
# cvs -d :pserver:anoncvs@cvs.freedesktop.org:/cvs/cairo co pycairo
buf = surface.get_data()
a = numpy.frombuffer(buf, numpy.uint8)
a.shape = (w, h, 4)
a[:,:,2] = 255
surface.write_to_png("triangle1.png") # red triangle..
# Alias the image as a pygame surface
import pygame
from time import sleep
imsurf = pygame.image.frombuffer(buf, (w,h), "RGBA")
depth = 4*8
pygame.display.init()
surface = pygame.display.set_mode((w,h), pygame.DOUBLEBUF, depth)
done = False
while not done:
surface.blit(imsurf, (0,0)) # blue triangle..
sleep(0.1)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
If you don't have a super new version of python-cairo bindings then use this instead:
#!/usr/bin/env python
import cairo
w, h = 128, 128
# Setup Cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
ctx = cairo.Context(surface)
# Set thickness of brush
ctx.set_line_width(15)
# Draw out the triangle using absolute coordinates
ctx.move_to(w/2, h/3)
ctx.line_to(2*w/3, 2*h/3)
ctx.rel_line_to(-1*w/3, 0)
ctx.close_path()
# Apply the ink
ctx.stroke()
#!/usr/bin/env python
import sys, cStringIO, pygame, pygame.locals
pygame.init()
f = cStringIO.StringIO()
surface.write_to_png(f)
screen = pygame.display.set_mode((w, h))
screen.fill((255, 255, 255))
f.seek(0)
pic = pygame.image.load(f,'temp.png').convert_alpha()
screen.blit(pic, (0, 0))
pygame.display.flip()
clock = pygame.time.Clock()
while True:
clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
raise SystemExit
JAPANESE PATTERN-DESIGNER. JAPANESE PATTERN-DESIGNER. All that warm afternoon we paid the tiresome penalty of having pushed our animals too smartly at the outset. We grew sedate; sedate were the brows of the few strangers we met. We talked in pairs. When I spoke with Miss Harper the four listened. She asked about the evils of camp life; for she was one of that fine sort to whom righteousness seems every man's and woman's daily business, one of the most practical items in the world's affairs. And I said camp life was fearfully corrupting; that the merest boys cursed and swore and stole, or else were scorned as weaklings. Then I grew meekly silent and we talked in pairs again, and because I yearned to talk most with Camille I talked most with Estelle. Three times when I turned abruptly from her to Camille and called, "Hark!" the fagged-out horses halted, and as we struck our listening pose the bugle's faint sigh ever farther in our rear was but feebly proportioned to the amount of our gazing into each other's eyes. "I'm glad you didn't," Bruce smiled. "What a sensation those good people will have presently! And most of them have been on intimate terms with our Countess. My darling, I shall never be easy in my mind till you are out of that house." Those manifestations of sympathy which are often so much more precious than material assistance were also repugnant to Stoic principles. On this subject, Epict¨ºtus expresses himself with singular harshness. ¡®Do not,¡¯ he says, ¡®let yourself be put out by the sufferings of your friends. If they are unhappy, it is their own fault. God made them for happiness, not for misery. They are grieved at parting from you, are they? Why, then, did they set their affections on things outside themselves? If they suffer for their folly it serves them right.¡¯93 You are awfully good, Daddy, to bother yourself with me, when you're ¡°Some strong, pungent liquid had been poured on the green necklace,¡± the letter from the millionaire stated. ¡°No alarm was given. My wife did not want to broadcast either the fact that she had the real gems or the trouble in the hotel. But people had heard the ¡®fire!¡¯ cry and doubtless some suspected the possible truth, knowing why she was getting ready. ¡°But the switches that control the motor for the drum are right out on the wall in plain sight,¡± he told himself, moving over toward them, since the rolling door was left wide open when the amphibian was taken out. ¡°Yes, here they all are¡ªthis one up for lifting the door, and down to drop it. And that switch was in the neutral¡ª¡®off¡¯¡ªposition when we were first here¡ªand it¡¯s in neutral now.¡± The strong sense, lively fancy, and smart style of his satires, distinguished also Pope's prose, as in his "Treatise of the Bathos; or, the Art of Sinking in Poetry;" his "Memoirs of P. P., Clerk of this Parish"¡ªin ridicule of Burnet's "Own Times"¡ªhis Letters, etc. In some of the last he describes the country and country seats, and the life there of his friends; which shows that, in an age more percipient of the charm of such things, he would have probably approached nearer to the heart of Nature, and given us something more genial and delightful than anything that he has left us. The taste for Italian music was now every day increasing; singers of that nation appeared with great applause at most concerts. In 1703 Italian music was introduced into the theatres as intermezzi, or interludes, consisting of singing and dancing; then whole operas appeared, the music Italian, the words English; and, in 1707, Urbani, a male soprano, and two Italian women, sang their parts all in Italian, the other performers using English. Finally, in 1710, a complete Italian opera was performed at the Queen's Theatre, Haymarket, and from that time the Italian opera was regularly established in London. This led to the arrival of the greatest composer whom the world had yet seen. George Frederick Handel was born at Halle, in Germany, in 1685. He had displayed wonderful genius for music as a mere child, and having, at the age of seven years, astonished the Duke of Saxe Weissenfels¡ªat whose court his brother-in-law was a valet¡ªwho found him playing the organ in the chapel, he was, by the Duke's recommendation, regularly educated for the profession of music. At the age of ten, Handel composed the church service for voices and instruments; and after acquiring a great reputation in Hamburg¡ªwhere, in 1705, he brought out his "Almira"¡ªhe proceeded to Florence, where he produced the opera of "Rodrigo," and thence to Venice, Rome, and Naples. After remaining in Italy four years, he was induced to come to England in 1710, at the pressing entreaties of many of the English nobility, to superintend the opera. But, though he was enthusiastically received, the party spirit which raged at that period soon made it impossible to conduct the opera with any degree of self-respect and independence. He therefore abandoned the attempt, having sunk nearly all his fortune in it, and commenced the composition of his noble oratorios. Racine's "Esther," abridged and altered by Humphreys, was set by him, in 1720, for the chapel of the Duke of Chandos at Cannons. It was, however, only by slow degrees that the wonderful genius of Handel was appreciated, yet it won its way against all prejudices and difficulties. In 1731 his "Esther" was performed by the children of the chapel-royal at the house of Bernard Gates, their master, and the following year, at the king's command, at the royal theatre in the Haymarket. It was fortunate for Handel that the monarch was German too, or he might have quitted the country in disgust before his fame had triumphed over faction and ignorance. So far did these operate, that in 1742, when he produced his glorious "Messiah," it was so coldly received that it was treated as a failure. Handel, in deep discouragement, however, gave it another trial in Dublin, where the warm imaginations of the Irish caught all its sublimity, and gave it an enthusiastic reception. On its next presentation in London his audience reversed the former judgment, and the delighted composer then presented the manuscript to the Foundling Hospital, where it was performed annually for the benefit of that excellent institution, and added to its funds ten thousand three hundred pounds. It became the custom, from 1737, to perform oratorios[156] on the Wednesdays and Fridays in Lent. Handel, whose genius has never been surpassed for vigour, spirit, invention, and sublimity, became blind in his latter years. He continued to perform in public, and to compose, till within a week of his death, which took place on April 13, 1759. The Deacon took his position behind a big black walnut, while he reconnoitered the situation, and got his bearings on the clump of willows. He felt surer than ever of his man, for he actually saw a puff of smoke come from it, and saw that right behind the puff stood a willow that had grown to the proportions of a small tree, and had its bark rubbed off by the chafing of driftwood against it. "Certainly. I see it very plainly," said the Surgeon, after looking them over. "Very absurd to start such a report, but we are quite nervous on the subject of smallpox getting down to the army. "Yes, just one." Reuben pulled up his chair to the table. His father sat at one end, and at the other sat Mrs. Backfield; Harry was opposite Reuben. Reuben counted them¡ªten. Then he pushed them aside, and began rummaging in the cart among cabbages and bags of apples. In a second or two he had dragged out five more rabbits. Robert stood with hanging head, flushed cheeks, and quivering hands, till his father fulfilled his expectations by knocking him down. HoMEBT ÏÂÔØ ÀïÃÀÓÈÀûæ«
ENTER NUMBET 0016hdelec.org.cn