cairo.pdf

(860 KB) Pobierz
1433786 UNPDF
Tutorialforthecl-cairo2package
Tam´asKPapp
August22,2007
1Introduction
Cairo isa2Dgraphicslibrarywithsupportformultipleoutputdevices.The cl-cairo2
packageprovidesCommonLispbindingsfortheCairoAPI. 1
cl-cairo2 iswrittenwiththefollowingprinciplesinmind:
CFFIbindingsaregeneratedbySWIG.ThisensuresthatAPIchangesarecaught
easilyandmakesiteasiertofollowthem.ThebindingstoCfunctionsarenotex-
porteddirectly.
ItattemptstomaketheinterfacemoreLisp-like.TheCairoAPIiswritteninC,
whichhasnogarbagecollectionorconditionhandling,andhaslittlesupportforso-
phisticateddynamicdatastructures.However,theLispusershouldnotworryabout
referencecountingandpointerarithmetic.InsteadofmerelyprovidingtheCwrappers,
cl-cairo2aimstoprovideaninterfaceconformingtothestyleofLispbetter.
Conditionhandling.IntheCairoAPI,anerrorissignaledbychangingthestateofthe
object,whichtheuserissupposedtoqueryperiodically.Thefunctionsincl-cairo2do
thisautomatically,anduseCommonLisp’spowerfulconditionfacilitytosignalerrors. 2
Thistutorialintroducescl-cairo2,butisnotanintroductiontoCairoitself.Ifyouare
notfamiliarwithCairo,itisrecommendedthatyourreadthe CairoTutorialforPython
1 Alternativesare cl-cairo, writtenbyLarsNostdalandothers(thisprojectappearstobedormant),and
ChristianHaselbach’s c±-cairo.
2 Thisfeatureisnotfullydevelopedyet:currentlyawarningissignalledforallerrors.Theframeworkis
inplace,Ijustneedtodecidewhicherrorsrequireuserintervention,etc.
1
1433786.005.png 1433786.006.png
cl-cairo2tutorial Tam´asKPapp
2Installationandloading
cl-cairo2usesASDF.Pleaserefertothe ASDF and ASDF-Install manualsonhowtoinstall
packages.YouneedtohavethelatestCairoAPIinstalled.OnDebiansystems,youjust
needtoinstallthe libcairo2 package.Youdon’tneedtheheaderfilesorSWIGunlessyou
plantoregenatetheSWIGbindings.
Onceinstalled,youcanloadcl-cairo2with
(asdf:operate’asdf:load-op:cl-cairo2)
3Gettingstarted
MostCairodrawingoperationsareperformedona context .Thinkofthecontextasa
combinationofacanvaswhichrememberspenstrokes(thecurrentpath),color,linewidth,
linestyle,andother,morecomplicatedsettingsthatdeterminewhatgetsdrawnwhere.
Whenyoubuildapath(whichyouwanttofillwithacolor/pattern,strokewithagivenline
style,orevensave),allofthishappensinacontext.
All cl-cairo2 functionsthatuseacontexttakeitastheirlastoptionalargument.If
notgiven,thesefunctionsuse *context* ,aspecialvariablethatstoresthedefaultcontext.
Contextsarecreatedfrom surfaces —which,atthispoint,shouldbethoughtofas
thebarecanvasitself(thinkofPDF,PostScript,ofPNGfiles).Contextsarecreatedfrom
surfaces.AllCairoobjects,includingcontextsandsurfaces,areimplementedinCLOS
wrappers,andcanbeclosed( destroyed )with destroy .
Whenthecontextiscreatedfromasurface,thereferencecount(intheinternalsof
Cairo)ofthelatterisincremented.Youcanimmediatelydestroythesurface:itwillnot
bedestroyed(iethefilewillnotbeclosed)untilyoudestroythecontext. 3 Thefollowing
codedrawsawhitediagonallineonabluebackground,usingaPostscriptfile–theresult
isshowninFigure1.
(defparameter*surface*(create-ps-surface "example.ps" 200100))
(setf*context*(create-context*surface*))
(destroy*surface*)
;;clearthewholecanvaswithblue
(rectangle00200100)
(set-source-rgb0.20.21)
(fill-path)
3 Thefilewillalsobeclosedifthewrapperobjectisgarbagecollected.However,youshouldnotrelyon
this,ascallingthegarbagecollectorisnotportable.
2
1433786.007.png 1433786.008.png
cl-cairo2tutorial Tam´asKPapp
;;drawawhitediagonalline
(move-to2000)
(line-to0100)
(set-source-rgb111)
(set-line-width5)
(stroke)
;;destroycontext,thisalsodestroysthesurfaceandclosesthefile
(destroy*context*)
Figure1:whitediagonallineonabluebackground
Unlessyouneedthesurfaceitselfforsomethingelse,youshouldusethe create-*-
context conveniencecommandsprovidedbycl-cairo2.Forexample,thefirstthreelinesof
thecodeabovewouldbereplacedby
(setf*context*(create-ps-context "example.ps" 200100))
UnliketheoriginalCairoAPI,surfacesandcontextsin cl-cairo2 remembertheirwidth
andheight.Usethegenericfunctions get-width and get-height toextractthese.
Whenyouwanttowritetheoutputintoabitmapfile(forexample,inPNGformat),you
firstneedtocreatean imagesurface ,thenwritethistothebitmapfilewhenyouaredone.
Themacro with-png-file willtakecareofthesedetails:useitlike
(with-png-file( "example.png" ’format-rgb24200100)
;;drawingcommands
...)
Thisexampleabovehighlightsanotherfeatureofcl-cairo2:constants(suchastheformat
specifier rgb24 )areexportedassimplenamesfromthecl-cairo2package.Internalfunctions
inthepackagemapthesetotheenumconstantsusedbyCairo.cl-cairo2useslookup
tables(assoclists)forthispurpose,whicharedefinedin tables.lisp .Cairoconstants
CAIRO PROPERTYSOMETHING usuallymaptotheLispsymbol property-something ,and
3
1433786.001.png
cl-cairo2tutorial Tam´asKPapp
canonlybeusedinsettingorquerying PROPERTY .Forexample, CAIRO_FORMAT_RGB24 is
mappedto format-rgb24 ,andusingitforsomeotherpropertywillcreateanerror.
Likewise,namesoftheLispfunctionareeasytodeducefromthenameoftheCfunction
intheCairoAPI:justdropthe cairo_ prefixandconvertallunderscores( _ )todashes( - ).
Theexceptionstothisrule(andtheexplanations)aregiveninTable3.
CairoAPIname(explanation) cl-cairo2name
cairo_fill (wouldconflictwith cl:fill ) fill-path
cairo_identity_matrix (wouldconflictwithmatrixalgebra
packages)
reset-trans-matrix
cairo_matrix_init_identity use (make-trans-matrix)
cairo_matrix_transform_distance transform-distance
cairo_matrix_transform_point transform-point
cairo_matrix_* trans-matrix-*
4Implementationnotes
4.1General
Thepackagecontainssomehelperfunctions,mostnotably deg-to-rad ,whichconverts
degreestoradians.Cairofunctionsusethelatter.
4.2Surfaces
Seethebeginningof surface.lisp forhelpermacrosusedinternallytodefinewrappersfor
theSWIG-generatedCFFIinterface(neithertheinterfacenotthesemacrosareexported).
with-alive-surface checksifthepointerforasurfaceobjectisnil,and check-surface-
pointer-status queriesthestatusofthesurfaceafterexecuting body . with-surface isa
combinationofthetwo,and new-surface-with-check makesanewsurfaceobjectfroma
pointer,checkingitsstatusfirst.
Currently,onlyPostscript,PDF,SVGandimagesurfaces(whichcanbewrittentoPNG
files)aresupported.
DrawinginX11windowsisimplementedusingthe x11-context class—seeSection4.7
formoreinformation.
4
1433786.002.png 1433786.003.png
cl-cairo2tutorial Tam´asKPapp
4.3Contexts
Contextsarerepresentedastheclass context ,whichcurrentlyonlyhasoneslot,apointer
tothecontext.Whencontextsaredestroyed,thisissetto nil .Asmentionedabove,the
defaultcontextis *context* ,anditisthedefaultforthelast(optional)argumentofeach
function.
Themacro with-context issimilarto with-surface above(itexecutesthebodywith
pointerpointingtotheobjectandthencheckserrorstatus).Thefunctions define-with
-default-context definesafunctionactingonacontextgivenalistofargumentsand
exportsthisfunction. define-flexible issimilar,butallowsamoreflexiblefunctionbody.
Functionsthatarenotimplementedyetinclude
cairo-get-target
push-group-with-content
get-group-target
set-source , set-source-surface , get-source
mask , mask-surface
IdoubtthatLispusersneed get/set-user-data or get-reference-count .Letmeknow
ifyoudo.
Sinceversion0.2.3,youcanusecolorsfrom cl-colors withthegenericfunction set-
source-color ,forexample,
(set-source-color+darkolivegreen+)
4.4Paths
AlmostalldrawingoperationsofCairorelyontheconstructionofpaths.Whilebasicpaths
canbeconstuctedinacontext,pathscanbesaved,modifiedandreusedindependently.At
themoment,cl-cairo2doesnotsupportthesepathoperations:
copy-path
copy-path-flat
path-destroy
append-path
ThisisbecauseIdecidedtofollowtherecommendationof relevantsection oftheCairoAPI
Manual,andimplementpathsandrelatedmanipulatorsinawaythatdoesn’trequirethe
usertotraversestructuresofCpointers.Thisisnotdoneyet.
glyph-path (seeSection4.5fordiscussionaboutglyphs)isnotimplementedeither.
5
1433786.004.png
Zgłoś jeśli naruszono regulamin