Cairo 图形指南(11) —— 图像
- 格式:doc
- 大小:808.50 KB
- 文档页数:9
图像基础图像(Picture)有多种含义,其中最常见的定义是指各种图形和影像的总称。
在理科的学习以及日常的学习或统计中,图像都是必不可少的组成部分,他为人类构建了一个形象的思维模式,有助于我们学习、思考问题。
基本信息词条信息【词目】图像【英文】image 【拼音】tú xiàng基本解释各种图形和影像的总称[picture;image] 绘制、摄制或印制的形象把电视机图像调亮些详细解释同“ 图象”。
晋傅咸《卞和画像赋》:“既铭勒於钟鼎,又图像於丹青。
” 北魏郦道元《水经注·漯水》:“其神图像,皆合青石为之。
”基本概念布图中呈现的任何单个的几何图形:(1)作为底图或布图一部分的绘制图形;(2)投影在屏幕上或目视的光学图像,通常经过若干倍的放大或缩小;(3)被氧化的硅片上刻蚀出的二氧化硅图像;(4)光学掩模版上及照相基片或干板上的乳胶层中的照相图像;(5)基片上的涂层经曝光和显影后呈现的光致抗蚀剂图形。
图像是由扫描仪、摄像机等输入设备捕捉实际的画面产生的数字图像。
由像素点阵构成的位图。
图像用数字任意描述像素点、强度和颜色。
描述信息文件存储量较大,所描述对象在缩放过程中会损失细节或产生锯齿。
在显示方面它是将对象以一定的分辨率分辨以后将每个点的色彩信息以数字化方式呈现,可直接快速在屏幕上显示。
分辨率和灰度是影响显示的主要参数。
图像适用于表现含有大量细节(如明暗变化、场景复杂、轮廓色彩丰富)的对象,如:照片、绘图等,通过图像软件可进行复杂图像的处理以得到更清晰的图像或产生特殊效果。
计算机中的图像从处理方式上可以分为位图和矢量图。
物理图像:在物理学中,物理图像是指以几何线条和几何符号等图形来形象地反映物理过程、物理现象或者物体与物质的各类特征和变化规律。
图像处理国际图像艺术推广机构君友会对图像处理流程的阐述是:图像处理是对图像进行分析、加工、和处理,使其满足视觉、心理以及其他要求的技术。
Cairo图形指南(2)分类:cairo 2D矢量图形库2011-05-20 14:44 68人阅读评论(0) 收藏举报Cairo 概念本文讲述Cairo 图形库中一些有用的定义/概念,理解它们可以帮助你更好的理解Cairo 绘图模型。
环境(Context)使用Cairo 绘图,必须要首先创建Cairo 环境(Context)。
Cairo 环境保存着所有的图形状态参数,这些参数描述了图形的构成,譬如线条宽度、颜色、要绘制的外观(Surface) 以及其它一些信息。
Cairo 环境允许真正的绘图函数使用很少的一部分参数,以此提高接口的易用性。
调用gdk_cairo_create () 函数可为所绘制的图形创建一个Cairo 环境。
cairo_t * cr;cr = gdk_cairo_create ( widget->window) ;这两行代码创建了一个Cairo 环境,并且这个Cairo 环境是关联到GdkDrawable 对象上的。
cairo_t 结构体包含了当前渲染设备的状态,也包含了所绘制图形的坐标。
从技术上来讲,cairo_t 就是所谓的Cairo 环境。
Cairo 所有的绘图函数都要去操作cairo_t 对象。
一个Cairo 环境可以被关联到一种特定的外观,譬如pdf、svg、png、GdkDrawable 等。
GDK 没有对Cairo API 进行封装,它只允许创建一个可基于GdkDrawable 对象绘制图形的Cairo 环境。
有一些GDK 函数可以将GDK 的矩形或填充区域转换为Cairo Path (路径),然后使用Cairo 绘图与渲染。
路径(Path)一条Path(路径)通常是由一条或多条首尾相接的直线段构成的,也可以由直线段与曲线段构成。
路径可分为Open(开放)类型与Closed (闭合)类型,前者的首尾端点不重合,后者的首尾端点重合。
在Cairo 中,绘图要从一条空路径开始,首先定义一条路径,然后通过绘制/填充操作使之可见。
Cairo绘制模型为了解释cairo使用的操作,我们先深入cairo绘制模型。
这涉及到仅几个概念,他们会一次又一次的应用于不同的函数。
首先我会介绍这些名词:目标(destination), 源(source), 蒙板(mask), 路径(path), 和上下文(context). 之后我会介绍一些动词,他们提供了操作名词的方式和创建你所希望的图形的方法.名词Cairo的名词有些抽象。
我提供了一些描述这些名词之间关系的图表,来使这些概念具体化。
前三个名词对应的就是这一节图中的三个层。
第四个名词路径当谈到它时把其画在了中间层上表示。
最后一个名词上下文在图上没有表示。
目标(Destination)目标就是用来在上面绘制的surface. 它可能是一个像素阵列,就和这篇教程中使用的一样,或者可能是一个SVG或PDF文件,或者其他别的东西。
当你使用图形元素的时候它们就被包含在Surface上,使用它可以建立复杂的工作就像在画布上绘制一样源(Source)就是你工作是用的“涂料”。
作为例子我把它显示为黑色,但是有有些半透明以显示它的下一层。
(看右图)和真正的涂料不一样的是,它不仅仅只是单一的颜色,可以是一个图案(pattern)或者之前创建的目标surface. 还和真正的涂料不一样的是源(Source)可以包含有透明度的信息----Alpha通道.蒙板(Mask)蒙板最重要的一点是:它控制着把源的哪些地方应用到目标上。
我把它显示为图中中间有一个洞的黄色的那个层,那个洞运行源通过。
当你使用一个绘制动词的时候,就像使用源在目标上盖了一个章。
凡是蒙板允许的地方源就被复制到目标。
蒙板不运行的地方对目标没有任何影响.路径(Path)路径在某种程度上是介于蒙板和上下文之间的一个东西。
我把它显示为蒙板层上的绿色的线。
它由路径相关的动词控制,可以被绘制动词使用.上下文(Context)上下文记录着可以影响动词的一切事物。
第一章海龟绘图基础海龟绘图是LOGO语言独有的特色。
它带领你走进一个五彩缤纷的图形世界,在这个世界里可以尽情的发挥你的想象,开拓你的思维,去挖掘图形的知识,去创造美,去享受美。
海龟绘图是LOGO语言的精华,适合少年儿童的思维发展。
因此,它是学习LOGO 语言的基础,是LOGO语言知识和程序设计竞赛的主要内容。
本章以概括总结的方式介绍海龟绘图的基础知识,以解决问题和完成任务的实践练习达到认识—掌握—熟练—创造性应用的目的。
第一节海龟绘图的环境LOGO语言现在普遍应用的有两个版本,一个是DOS操作系统下的LOGO4.0版本,另一个是WINDOWS操作系统下的WINDOWS版本。
DOS版本与WINDOWS版本在命令功能方面基本相同,所编程序基本可以通用。
由于WINDOWS版本是窗口式操作,许多功能的实现优于DOS版本,灵活方便又有汉字功能,所以我们提倡在安装了WINDOWS操作系统的机器上都使用WINDOWS版本。
本书讲述和应用的就是WINDOWS版本。
一、主要常用窗口的功能及其应用图 1.1.1图 1.1.2图 1.1.3以上三个LOGO语言屏幕窗口图形是初学海龟绘图和LOGO语言最常用的窗口和屏幕形式,是必须熟练掌握的。
图 1.1.1是启动LOGO语言后首先进入的屏幕形式。
它由系统窗口和平铺其上的绘图窗口、命令窗口组成。
这就具备了海龟绘图的基本环境条件,可以在命令窗口输入命令、命令组或编制执行简单过程指挥海龟绘图了。
图 1.1.2 又打开一个“编辑器”窗口。
编辑器是专为编辑过程程序而提供的,其功能为:1.编辑过程程序和文本文件;2.将程序定义到内存并检查是否有错,如果有错则在命令窗口给出错误提示,否则提示定义成功,在命令窗口可反复执行定义过的过程程序,在编辑窗口可反复修改过程程序,直到满意;3.编辑好的过程程序以*.LGO文件形式存盘;文本以*.TXT文件形式存盘;4.调入LOGO程序文件定义到内存执行或执行前三项功能。
cairo[02]Windows环境学习笔记——cairo的绘图概念cairo的与众不同的概念cairo的开发者为cairo的绘图⽅式做了⼀个抽象的描述。
在cairo的函数中,分两⼤类:名词和动词。
我们先来看名词,它们有: desitnation:⽬的地,这⾥可以理解为⽬标对象 source:源,这⾥相当于是我们绘图的素材 mask:⾯具,这⾥理解为⼀个模具,接下来会详解 path:路径,和D2D的路径有⼀点像,只是更简单 context:可以说是⼀个事件记录器destination和source——⽬标和素材⽬标,在cairo中特指我们绘图的那⼀块区域。
cairo给出的术语是surface(表⾯)。
⼀个⽬标⼏乎可以是任何⼀个cairo⽀持的东西:⼀张png,⼀个PDF,或是我们想要的屏幕上的⼀块像素点。
这个表⾯会像⼀块画布⼀样,⼀点⼀点积累我们绘制的东西。
素材,cairo的介绍是将它当作是⼀个画家的颜料。
它可以是⼀个颜⾊,还可以是⼀张图⽚或是之前我们介绍的⽬标对象,它也有alpha值。
所以我们的绘图就开始变得有点像剪贴画了。
剪贴画的剪⼑我们的绘图/剪贴画总不能只是⼀个⼜⼀个的矩形,除⾮你特别喜欢像素风格。
所以,mask的概念就出来了。
将其理解为⼀个模具毫不违背它的设计原因。
它的作⽤是覆盖素材的⼀部分,或是更准确来说,让素材的⼀部分通过它呈现到⽬标上,达到不同图形的效果。
⽽path则是我们剪⼑的⽅向路径。
context在cairo⾥,所有的素材都要被存在⼀个context⾥。
⼀个context可以存储⼀个素材、⼀个⽬标和⼀个模具。
最最重要的是,他还追踪⼀个路径的变化。
cairo⽤⼀个类来存储context:cairo_t。
cairo的动词cairo的绘图是通过将素材和模具放在⽬标上⾯,然后将这些“图层”压成⼀张呈现出来的图像。
接下来的五个动词将会展现cairo对模具的操作。
stroke:在模具上透出线来,让素材通过。
Package‘Cairo’November28,2023Version1.6-2Title R Graphics Device using Cairo Graphics Library for CreatingHigh-Quality Bitmap(PNG,JPEG,TIFF),Vector(PDF,SVG,PostScript)and Display(X11and Win32)OutputAuthor Simon Urbanek<***************************>,Jef-frey Horner<**************************>Maintainer Simon Urbanek<***************************>Depends R(>=2.4.0)Imports grDevices,graphicsSuggests pngEnhances FastRWebDescription R graphics device using cairographics library that can be used to create high-quality vec-tor(PDF,PostScript and SVG)and bitmap output(PNG,JPEG,TIFF),and high-quality render-ing in displays(X11and Win32).Since it uses the same back-end for all output,copy-ing across formats is WYSIWYG.Files are created without the dependence on X11or other ex-ternal programs.This device supports alpha channel(semi-transparent drawing)and result-ing images can contain transparent and semi-transparent regions.It is ideal for use in server envi-ronments(file output)and as a replacement for other devices that don't have Cairo's capabili-ties such as alpha support or anti-aliasing.Backends are modular such that any subset of back-ends is supported.License GPL-2|GPL-3SystemRequirements cairo(>=1.2/)URL /Cairo/NeedsCompilation yesRepository CRANDate/Publication2023-11-2808:44:24UTCR topics documented:Cairo (2)Cairo.capabilities (5)1Cairo.capture (6)Cairo.onSave (7)Cairo.serial (8)CairoFonMatch (8)CairoFonts (10)Index12 Cairo Create a new Cairo-based graphics deviceDescriptionCairo initializes a new graphics device that uses the cairo graphics library for rendering.The current implementation produces high-quality PNG,JPEG,TIFF bitmapfiles,high resolution PDF files with embedded fonts,SVG graphics and PostScriptfiles.It also provides X11and Windows interactive graphics devices.Unlike other devices it supports all graphics features including alpha blending,anti-aliasing etc.CairoX11,CairoPNG,CairoPDF,CairoPS and CairoSVG are convenience wrappers of Cairo that take the same arguments as the corresponding device it replaces such as X11,png,pdf,e of the Cairo function is encouraged as it is moreflexible than the wrappers.UsageCairo(width=640,height=480,file="",type="png",pointsize=12,bg="transparent",canvas="white",units="px",dpi="auto",...)CairoX11(display=Sys.getenv("DISPLAY"),width=7,height=7,pointsize=12,gamma=getOption("gamma"),bg="transparent",canvas="white",xpos=NA,ypos=NA,...)CairoPNG(filename="Rplot%03d.png",width=480,height=480,pointsize=12,bg="white",res=NA,...)CairoJPEG(filename="Rplot%03d.jpeg",width=480,height=480,pointsize=12,quality=75,bg="white",res=NA,...) CairoTIFF(filename="Rplot%03d.tiff",width=480,height=480,pointsize=12,bg="white",res=NA,...)CairoPDF(file=ifelse(onefile,"Rplots.pdf","Rplot%03d.pdf"),width=6,height=6,onefile=TRUE,family="Helvetica",title="R Graphics Output",fonts=NULL,paper="special",encoding,bg,fg,pointsize,pagecentre,...)CairoSVG(file=ifelse(onefile,"Rplots.svg","Rplot%03d.svg"),width=6,height=6,onefile=TRUE,bg="transparent",pointsize=12,...)CairoWin(width=7,height=7,pointsize=12,record=getOption("graphics.record"),rescale=c("R","fit","fixed"),xpinch,ypinch,bg="transparent",canvas="white",gamma=getOption("gamma"),xpos=NA,ypos=NA,buffered=getOption("windowsBuffered"),restoreConsole=FALSE,...)CairoPS(file=ifelse(onefile,"Rplots.ps","Rplot%03d.ps"),onefile=TRUE,family,title="R Graphics Output",fonts=NULL,encoding,bg,fg,width,height,horizontal,pointsize,paper,pagecentre,print.it,command,colormodel)Argumentswidth width of the plot area(also see units).height height of the plot area(also see units).file name of thefile to be created or connection to write to.Only PDF,PS andPNG types support connections.For X11type file specifies the display name.If NULL or""a reasonable default will be chosen which is"plot.type"forfile-oriented types and value of the DISPLAY environment variable for X11.Forimage types thefile name can contain printf-style formatting expecting one inte-ger parameter which is the page number,such as"Rplot%03d.png".The pagenumbers start at one.Thefilename is expanded using path.expand.type output type.This version of Cario supports"png","jpeg"and"tiff"bitmaps(png/tiff with transparent background),"pdf"PDF-file with embedded fonts,"svg"SVG-file,"ps"PostScript-file,"x11"X11interactive window and"win"Windows graphics.A special type"raster"creates an image back-end that pro-duces no actual outputfile but can be used in conjunction with any of dev.capture(),grid.cap()or Cairo:::.image()to create in-memory images.Depending onthe support of various backends in cairo graphics some of the options may notbe available for your system.See Cairo.capabilities function.pointsize initial text size(in points).canvas canvas color(must be opaque).The canvas is only used by devices that displaygraphics on a screen and the canvas is only visible only if bg is transparent.bg plot background color(can include alpha-component or be transparent allto-gether).units units for of the width and height specifications.It can be any of"px"(pixels),"in"(inches),"pt"(points),"cm"(centimeters)or"mm"(millimeters).dpi DPI used for the conversion of units to pixels.If set to"auto"the DPI resolutionwill be determined by the back-end....additional backend specific parameters(e.g.quality setting for JPEG(0..100),compression for TIFF(0,1=none,5=LZW(default),7=JPEG,8=Adobe De-flate),locator for a custom locator function in image back-ends)The PDF back-end supports following additional arguments:author,subject,creator,keywords,create.date and modify.date.If specified,all of theabove must be single strings.The dates must be in PDF-defined format,you canuse something like paste0("D:",gsub("[-:]","",.POSIXct(Sys.time(),"GMT"))),"Z")to convert from POSIXct to PDF format.In addition,the version argument(asdocumented in pdf)can be either a string or a scalar real number.However,thecairographics library only supports values1.4and1.5.All parameters listed below are defined by the other devices are are used by thewrappers to make it easier replace other devices by Cairo.They are describedin detail in the documentation corresponding to the device that is being replaced.display X11display,see X11gamma gamma correctionxpos see X11ypos see X11filename same as file in Cairores resolution in ppi,see png,will override dpi in Cairo if set to anything other than NA or NULL.Note that cairographics does not support tagging PNG outputfileswith DPI so the raster image will be produced with the dpi setting,but readersmay render it at some default dpi setting.quality quality of the jpeg,see jpegonefile logical:if true(the default)allow multiplefigures in onefile(see pdf).false is currently not supported by vector devicesfamily font family,see pdftitle see pdffonts see pdf,ignored,Cairo automatically detects and embeds fontspaper see pdf(ignored,Cairo uses device dimensions)encoding see pdf(ignored,Cairo uses native enconding except for symbols)fg see pdf(ignored)pagecentre see pdf(ignored,Cairo uses device dimensions and thus it is irrelevant)record Windows-specific,ignored on unixrescale Windows-specific,ignored on unixxpinch Windows-specific,ignored on unixypinch Windows-specific,ignored on unixbuffered Windows-specific,ignored on unixrestoreConsole Windows-specific,ignored on unixhorizontal see postscript(ignored)print.it see postscript(ignored)command see postscript(ignored)colormodel see postscript(ignored,Cairo always uses RGB or ARGB)ValueThe(invisible)return value is NULL if the device couldn’t be created or a Cairo object if successful.The vaule of the object is the device number.Cairo.capabilities5 Known issues•The X11backend is quite slow.The reason is the cairographics implementation of the back-end,so we can’t do much about it.It should be possible to drop cairographics’Xlib backend entirely and use image backend copied into an X11window instead.We may try that in future releases.•TrueType(and OpenType)fonts are supported when this package is compiled against a cairo graphics library configured with FreeType and Fontconfig support.Therefore make sure havea cairo graphics library with all bells and whistles to get a good result.•R math symbols are supported,but require a TrueType"Symbol"font accessible to Cairo under that name.See AlsoCairoFontsExamples#very simple KDECairo(600,600,file="plot.png",type="png",bg="white")plot(rnorm(4000),rnorm(4000),col="#ff000018",pch=19,cex=2)#semi-transparent reddev.off()#creates a file"plot.png"with the above plot#you can use any Cairo backend and get the same result#vector,bitmap or on-screenCairoPDF("plot.pdf",6,6,bg="transparent")data(iris)attach(iris)plot(Petal.Length,rep(-0.03,length(Species)),xlim=c(1,7),ylim=c(0,1.7),xlab="Petal.Length",ylab="Density",pch=21,cex=1.5,col="#00000001",main="Iris(yet again)",bg=c("#ff000020","#00ff0020","#0000ff20")[unclass(Species)])for(i in1:3)polygon(density(Petal.Length[unclass(Species)==i],bw=0.2),col=c("#ff000040","#00ff0040","#0000ff40")[i])dev.off()##remove the example files if not in an interactive sessionif(!interactive())unlink(c("plot.png","plot.pdf"))Cairo.capabilities Reports which output types are supported by this Cairo buildDescriptionCairo.capabilities returns a logical vector describing the capabilities of this particular Cairo build.6Cairo.captureUsageCairo.capabilities()DetailsThe Cairo package provides multiple back-ends,such as images(PNG,JPEG,TIFF),vector graph-ics(PDF,PostScript,SVG)or displays(X11,Windows).However,not all systems support all back-ends.The Cairo.capabilities function returns a logical vector showing which capabilities are supported in this particular Cairo build.Note that the capabilities depend both on the libraries available in the system as well as the compiled-in modules in cairo graphics.See AlsoCairoCairo.capture Capture contents of an image backend or a display list snapshot.DescriptionCairo.capture is essentially the same as dev.capture(native=TRUE)with the exception that it works where dev.capture doesn’t such as onSave callbacks.Cairo.snapshot is very similar to recordPlot except it also allows to retrieve the last snapshot. UsageCairo.capture(device=dev.cur())Cairo.snapshot(device=dev.cur(),last=FALSE)Argumentsdevice device number or an object of the class Cairo(as obtained from the Cairofunction).last logical,if FALSE then a new snapshot is created(exactly the same as recordPlot()), if TRUE then the last known snapshot is retrieved,if NA then a snapshot is createdfirst,but if the display list is empty last snapshot is retrieved instead.ValueCairo.capture:object of the class nativeRaster.Cairo.snapshot:object of the class recordedplot.Author(s)Simon UrbanekCairo.onSave7 Cairo.onSave Cairo callbacksDescriptionCairo.onSave set the onSave callback which allows R code to be run when Cairofinalizes a page (either due to a new page being created or by the device being closed).The callback expects function(device,page)where device will be the device number and page is the currentlyfin-ished page number(starting at1).UsageCairo.onSave(device=dev.cur(),onSave)Argumentsdevice device number or Cairo object(as returned by the Cairo function)onSave function that will replace the current callback or NULL to remove the current callbackValueThe old callback being replaced or NULL if there was none.NoteThe function onSave will be evaluated in the global environment and no error checking is done,so you must make sure to catch errors,otherwise the behavior is undefined(and may included crashing R or other bad things).Author(s)Simon UrbanekSee AlsoCairoExamplesif(require(png,quietly=TRUE)){dev<-Cairo(800,600,type= raster )Cairo.onSave(dev,function(dev,page).GlobalEnv$png<-writePNG(Cairo.capture(dev)))plot(1:10,col=2)dev.off()str(png)}Cairo.serial Check for changes in the graphics state of Cairo devices.DescriptionCairo.serial returns an integer that is increased with every plotting operation on the device.This allows user code to determine whether any new content has been added to the device since it was last checked.UsageCairo.serial(device=dev.cur())Argumentsdevice device number or an object of the class Cairo(as obtained from the Cairo function).ValueInteger value.NoteThe integer value overflows to0at2^31.Typically only equality should be checked and for such it is extremely unlikely that the state has changed yet the serial value is the same due to overflow.Author(s)Simon UrbanekCairoFonMatch Find installed fonts with a fontconfig patternDescriptionCairoFontMatch searches for fonts based on a fontconfig pattern.UsageCairoFontMatch(fontpattern="Helvetica",sort=FALSE,verbose=FALSE)Argumentsfontpattern character;a fontconfig pattern.sort logical;if’FALSE’,display only the best matching font for the pattern.If’TRUE’,display a sorted list of best matching fonts.verbose logical;if’FALSE’,display the family,style,andfile property for the pattern.if’TRUE’,display the canonical font pattern for each match.DetailsThis function displays a list of one or more fonts matching the supplied fontconfig pattern.sort=’FALSE’displays the font that Cairo will use for the supplied pattern,while sort=’TRUE’displays a sortedlist of best matching fonts.The simplest fontconfig pattern matching all installed fonts is":".Here’swhat CairoFontMatch(":")displays on this system:1.family:"Bitstream Vera Sans",style:"Roman",file:"/usr/share/fonts/truetype/ttf-bitstream-vera/verbose=’FALSE’displays the font properties’family’,’style’,and’file’,while verbose=’TRUE’will display the canonical font pattern,displaying all properties known for the font(output of Cairo-FontMatch(":",verbose=TRUE)):1.family:"Bitstream Vera Sans",style:"Roman",file:"/usr/share/fonts/truetype/ttf-bitstream-vera/"Bitstream Vera Sans-12:familylang=en:style=Roman:stylelang=en:slant=0:weight=80:width=100:pixelsiA simple approach to selecting a font starts with calling CairoFontMatch(":",sort=TRUE)to list allavailable fonts.Next,the user will choose a font from the list and call CairoFontMatch("FamilyName:style=PreferredStyle",so substituting"FamilyName"and"PreferredStyle"with the desired values.If only one font is found,then the user has found the fontconfig pattern that will select the desired font.Otherwise,the userwill call CairoFontMatch with verbose=TRUE to determine other properties to add to the pattern toattain the desired font,for instance the fontformat.The following excerpt is from the fontconfig user’s manual(http://fontconfi/)and better de-scribes the fontconfig pattern definition:"Fontconfig provides a textual representation for patterns that the library can both accept and gen-erate.The representation is in three parts,first a list of family names,second a list of point sizesandfinally a list of additional properties:<families>-<point sizes>:<name1>=<values1>:<name2>=<values2>...Values in a list are separated with commas.The name needn’t include either families or point sizes;they can be elided.In addition,there are symbolic constants that simultaneously indicate both aname and a value.Here are some examples:Font Pattern Meaning----------------------------------------------------------Times-1212point Times RomanTimes-12:bold12point Times BoldCourier:italic Courier Italic in the default sizeMonospace:matrix=1.101The users preferred monospace fontwith artificial obliquing10CairoFonts The’\’,’-’,’:’and’,’characters in family names must be preceeded by a’\’character to avoid having them misinterpreted.Similarly,values containing’\’,’=’,’_’,’:’and’,’must also have them preceeded by a’\’character.The’\’characters are stripped out of the family name and values as the font name is read."Known issues•This function is only available when the Cairo graphics library is configured with FreeType and FontConfig support.See AlsoCairoFonts,CairoCairoFonts Set the fonts used for all Cairo graphics devices.DescriptionCairoFonts initializes the fonts used for Cairo graphics devices.UsageCairoFonts(regular="Helvetica:style=Regular",bold="Helvetica:style=Bold",italic="Helvetica:style=Italic",bolditalic="Helvetica:style=Bold Italic,BoldItalic",symbol="Symbol",usePUA=TRUE)Argumentsregular character;fontconfig pattern for the’plain text’font.bold character;fontconfig pattern for the’bold face’font.italic character;fontconfig pattern for the’italic’font.bolditalic character;fontconfig pattern for the’bold italic’font.symbol character;fontconfig pattern for the’symbol’font.usePUA logical;if FALSE then symbols are using regular Unicode code points(supported by regular fonts),otherwise Private Unicode Area(PUA)of symbols is used(typically better propulated by specialized symbol fonts).R4.0.0or higher isrequired for usePUA=FALSE.CairoFonts11DetailsThis function sets the fonts for Cairo graphics devices globally;previously opened Cairo graphics devices will also use these fonts.The argument names correspond to thefive values of the graphical parameter’font’,i.e.regular is1,bold is2,italic is3,etc.For an explanation of fontconfig patterns,see CairoFontMatch.Known issues•This function is only available when the cairo graphics library is configured with FreeType and Fontcofig support.•R math symbols are supported,but require a"Symbol"font with the Adobe Symbol Encoding unless usePUA=FALSE is used(available in R4.0.0or higher only).See AlsoCairoFontMatch,Cairo,par,Examples##Not run:##The following fontconfig patterns define the free truetype fonts#available in the debian package ttf-freefont .##Freesans is very similar to HelveticaCairoFonts(regular="FreeSans:style=Medium",bold="FreeSans:style=Bold",italic="FreeSans:style=Oblique",bolditalic="FreeSans:style=BoldOblique")##End(Not run)Index∗deviceCairo,2Cairo.capabilities,5Cairo.capture,6Cairo.onSave,7Cairo.serial,8CairoFonMatch,8CairoFonts,10Cairo,2,6–8,10,11Cairo.capabilities,3,5Cairo.capture,6Cairo.onSave,7Cairo.serial,8Cairo.snapshot(Cairo.capture),6 CairoFonMatch,8CairoFontMatch,11CairoFontMatch(CairoFonMatch),8 CairoFonts,5,10,10CairoJPEG(Cairo),2CairoPDF(Cairo),2CairoPNG(Cairo),2CairoPS(Cairo),2CairoSVG(Cairo),2CairoTIFF(Cairo),2CairoWin(Cairo),2CairoX11(Cairo),2jpeg,4par,11path.expand,3pdf,3,4png,4postscript,4X11,412。
Cairo图形指南安装Cairo要在您的项目中使用Cairo,首先需要安装它。
Cairo可以使用包管理器来安装,例如对于Python,可以使用pip安装:pip install pycairo对于其他编程语言,可以参考Cairo的官方文档中的安装指南。
创建Cairo绘图使用Cairo创建绘图首先需要创建一个Cairo表面(surface)对象。
表面对象表示了一个绘图的目标,可以是图像、窗口或PDF文档等。
在Cairo中,有几种类型的表面可供选择,包括图像表面、PDF表面、SVG 表面等。
接下来,需要创建一个Cairo上下文(context)对象。
上下文对象是进行绘图操作的实例,可以通过调用表面对象的方法来创建。
下面是一个创建图像表面和上下文对象的示例(使用Python):import cairosurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)context = cairo.Context(surface)绘制基本形状有了上下文对象,就可以开始绘制各种基本形状,例如线条、矩形和圆。
绘制线条:context.move_to(x1, y1) # 设置起点context.line_to(x2, y2) # 设置终点context.stroke( # 绘制线条绘制矩形:context.rectangle(x, y, width, height) # 设置矩形参数context.stroke( # 绘制矩形边框绘制圆:context.arc(x, y, radius, start_angle, end_angle) # 设置圆的参数context.stroke( # 绘制圆的边框填充形状除了绘制形状的边框,还可以使用Cairo来填充形状的内部。
填充矩形:context.rectangle(x, y, width, height) # 设置矩形参数context.fill( # 填充矩形填充圆:context.arc(x, y, radius, start_angle, end_angle) # 设置圆的参数context.fill( # 填充圆字体和文本设置字体:context.select_font_face("font_family",cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)context.set_font_size(font_size)绘制文本:context.move_to(x, y) # 设置文本起点context.show_text("text") # 显示文本导出图像完成绘图后,可以将图像导出为PNG、PDF、SVG等格式。
Cairo 图形指南 (11) —— 图像在这一篇里,要讲述图像的处理。
先是演示如何在 GTK+ 窗口中显示一幅图像,然后再制造一些特效。
图像的显示在第一个例子里,显示了一幅图像。
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #include <cairo.h>#include <gtk/gtk.h>cairo_surface_t *image;static gbooleanon_expose_event(GtkWidget *widget,GdkEventExpose *event,gpointer data){cairo_t *cr;cr = gdk_cairo_create (widget->window);cairo_set_source_surface(cr, image, 10, 10);cairo_paint(cr);cairo_destroy(cr);return FALSE;}int main(int argc, char *argv[]){GtkWidget *window;image = cairo_image_surface_create_from_png("plaveckycastle.png");gtk_init(&argc, &argv);window = gtk_window_new(GTK_WINDOW_TOPLEVEL);34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 g_signal_connect(window, "expose-event",G_CALLBACK (on_expose_event), NULL);g_signal_connect(window, "destroy",G_CALLBACK (gtk_main_quit), NULL);gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 320, 250); gtk_widget_set_app_paintable(window, TRUE);gtk_widget_show_all(window);gtk_main();cairo_surface_destroy(image);return 0;}这个示例显示了一幅图片,其尺寸为 300x225,可从这里下载。
这是斯洛伐克西部一个什么地方(Plavecke Podhradie )的中世纪城堡的废墟的一幅照片。
?1 i mage = cairo_image_surface_create_from_png("plaveckycastle.png"); 用一幅 png 图片来创建一份图像外观。
出于效率的考虑,应在主函数中调用这个函数。
?1 c airo_set_source_surface(cr, image, 10, 10);基于前面构造的图像外观来创建源与外观,用于图像的绘制。
?1 c airo_paint(cr);绘制图片。
垂帘效果(Blind Down )在下面的代码示例中,要垂帘显示图片,就像拉下窗帘的那种效果。
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <cairo.h>#include <gtk/gtk.h>gboolean timer = TRUE;cairo_surface_t *image;static gbooleanon_expose_event(GtkWidget *widget,GdkEventExpose *event,gpointer data){cairo_t *cr;cairo_t *ic;cairo_surface_t *surface;static gdouble angle = 0;static gint image_width = 0;static gint image_height = 0;22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65static gint w = 0;static gint h = 0;cr = gdk_cairo_create(widget->window);gint width, height;gtk_window_get_size(GTK_WINDOW(widget), &width, &height);image_width = cairo_image_surface_get_width(image);image_height = cairo_image_surface_get_height(image);w = image_width;surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, image_width, image_height);ic = cairo_create(surface);cairo_rectangle(ic, 0, 0, w, h);cairo_fill(ic);h += 1;if ( h == image_height) timer = FALSE;cairo_set_source_surface(cr, image, 10, 10);cairo_mask_surface(cr, surface, 10, 10);cairo_surface_destroy(surface);cairo_destroy(cr);cairo_destroy(ic);return FALSE;}static gbooleantime_handler(GtkWidget *widget){if (widget->window == NULL) return FALSE;if (!timer) return FALSE;gtk_widget_queue_draw(widget);return TRUE;}66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 int main(int argc, char *argv[]){GtkWidget *window;image = cairo_image_surface_create_from_png("plaveckycastle.png");gtk_init(&argc, &argv);window = gtk_window_new(GTK_WINDOW_TOPLEVEL);g_signal_connect(G_OBJECT(window), "expose-event",G_CALLBACK(on_expose_event), NULL);g_signal_connect(G_OBJECT(window), "destroy",G_CALLBACK(gtk_main_quit), NULL);gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 325, 250); gtk_window_set_title(GTK_WINDOW(window), "blind down");gtk_widget_set_app_paintable(window, TRUE);g_timeout_add(15, (GSourceFunc) time_handler, (gpointer) window);gtk_widget_show_all(window);gtk_main();cairo_surface_destroy(image);return 0;}这个垂帘效果幕后的思想相当简单。
图片的高度是 h 个像素,则可对其逐行进行绘制,直至图片完全显示。
?1 2 cairo_t *cr;cairo_t *ic;声明两个 cairo 环境,一个与 GtkWindow 相关联,另一个与图片相关联。
?1 2 surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, image_width, image_height); ic = cairo_create(surface);创建一个图像外观,并通过它构造那个与图像相关联的 cairo 环境。
?1 2 cairo_rectangle(ic, 0, 0, w, h);cairo_fill(ic);在初始的空图像中绘制一个矩形,它在循环显示中会增加 1 个像素的高度。
采用这种方式创建的图像在后面要作为蒙板来用。
?1 2 h += 1;if ( h == image_height) timer = FALSE;整幅图像绘制完毕后,停止计时器。
?1 2 cairo_set_source_surface(cr, image, 10, 10);cairo_mask_surface(cr, surface, 10, 10);城堡图像被设置为要被绘制的源,并采用 surface 的 alpha 通道作为蒙板来绘制这个源。
光谱效果将这种效果称为光谱效果,因为作者不知道怎么称呼才好(我感觉叫百叶窗效果更好)。
可能你还记得从前的 ZX 光谱计算机,在这种计算机上载入图像时,它就逐渐的被显示出来,下面的示例大致是模仿这种方式。
?1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637383940414243 #include <cairo.h>#include <gtk/gtk.h>gboolean timer = TRUE;cairo_surface_t *image;static gbooleanon_expose_event(GtkWidget *widget,GdkEventExpose *event,gpointer data){cairo_t *cr;cairo_t *ic;cairo_surface_t *surface;static gdouble angle = 0;static gint w = 0;static gint h = 0;static gint image_width = 0;static gint image_height = 0;static gint count = 0;cr = gdk_cairo_create(widget->window);gint width, height;gtk_window_get_size(GTK_WINDOW(widget), &width, &height);surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, image_width, image_height);image_width = cairo_image_surface_get_width(image);image_height = cairo_image_surface_get_height(image);w = image_width;ic = cairo_create(surface);gint i, j;for (i = 0; i <= image_height; i+=7) {for (j=0 ; j < count; j++) {4445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 cairo_move_to(ic, 0, i+j);cairo_line_to(ic, w, i+j);}}count++;if ( count == 8) timer = FALSE;cairo_stroke(ic);cairo_set_source_surface(cr, image, 10, 10);cairo_mask_surface(cr, surface, 10, 10);cairo_surface_destroy(surface);cairo_destroy(cr);cairo_destroy(ic);return FALSE;}static gbooleantime_handler (GtkWidget *widget){if (widget->window == NULL) return FALSE;if (!timer) return FALSE;gtk_widget_queue_draw(widget);return TRUE;}int main(int argc, char *argv[]){GtkWidget *window;image =cairo_image_surface_create_from_png("plaveckycastle.png"); gtk_init(&argc, &argv);window = gtk_window_new(GTK_WINDOW_TOPLEVEL);g_signal_connect(G_OBJECT(window), "expose-event",G_CALLBACK(on_expose_event), NULL);88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 g_signal_connect(G_OBJECT(window), "destroy",G_CALLBACK(gtk_main_quit), NULL);gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 325, 250);gtk_widget_set_app_paintable(window, TRUE);g_timeout_add(400, (GSourceFunc) time_handler, (gpointer) window);gtk_widget_show_all(window);gtk_main();cairo_surface_destroy(image);return 0;}这个示例的许多细节与上一个示例相似。