Tải bản đầy đủ - 0 (trang)
Chapter 8. 2D and 3D Graphics

Chapter 8. 2D and 3D Graphics

Tải bản đầy đủ - 0trang

reports.

AnalternativetoQPainteristouseOpenGL.OpenGLisa

standardlibraryfordrawing2Dand3Dgraphics.TheQtOpenGL

modulemakesitveryeasytointegrateOpenGLcodeintoQt

applications.







PaintingwithQPainter

Tostartpaintingtoapaintdevice(typicallyawidget),we

simplycreateaQPainterandpassapointertothedevice.For

example:

voidMyWidget::paintEvent(QPaintEvent*event)

{

QPainterpainter(this);

...

}



WecandrawvariousshapesusingQPainter'sdraw...()functions.

Figure8.1liststhemostimportantones.Thewaythedrawing

isperformedisinfluencedbyQPainter'ssettings.Someofthese

areadoptedfromthedevice,othersareinitializedtodefault

values.Thethreemainpaintersettingsarethepen,thebrush,

andthefont:

Thepenisusedfordrawinglinesandshapeoutlines.It

consistsofacolor,awidth,alinestyle,acapstyle,anda

joinstyle.

Thebrushisthepatternusedforfillinggeometricshapes.It

normallyconsistsofacolorandastyle,butcanalsobea

texture(apixmapthatisrepeatedinfinitely)oragradient.

Thefontisusedfordrawingtext.Afonthasmany

attributes,includingafamilyandapointsize.



Figure8.1.QPainter'smostfrequentlyused



draw...()functions



ThesesettingscanbemodifiedatanytimebycallingsetPen(),

setBrush(),andsetFont()withaQPen,QBrush,orQFontobject.



Figure8.2.Capandjoinstyles



Figure8.3.Penstyles



Figure8.4.Predefinedbrushstyles



[Viewfullsizeimage]



Let'sseeafewexamplesinpractice.Here'sthecodetodraw

theellipseshowninFigure8.5(a):



QPainterpainter(this);

painter.setRenderHint(QPainter::Antialiasing,true);

painter.setPen(QPen(Qt::black,12,Qt::DashDotLine,Qt::RoundCa

painter.setBrush(QBrush(Qt::green,Qt::SolidPattern));

painter.drawEllipse(80,80,400,240);



Figure8.5.Geometricshapeexamples



[Viewfullsizeimage]



ThesetRenderHint()callenablesantialiasing,tellingQPaintertouse

differentcolorintensitiesontheedgestoreducethevisual

distortionthatnormallyoccurswhentheedgesofashapeare

convertedintopixels.Theresultissmootheredgesonplatforms

anddevicesthatsupportthisfeature.

Here'sthecodetodrawthepiesegmentshowninFigure8.5

(b):



QPainterpainter(this);

painter.setRenderHint(QPainter::Antialiasing,true);

painter.setPen(QPen(Qt::black,15,Qt::SolidLine,Qt::RoundCap,

Qt::MiterJoin));

painter.setBrush(QBrush(Qt::blue,Qt::DiagCrossPattern));

painter.drawPie(80,80,400,240,60*16,270*16);



ThelasttwoargumentstodrawPie()areexpressedinsixteenths

ofadegree.

Here'sthecodetodrawthecubicBéziercurveshowninFigure

8.5(c):

QPainterpainter(this);

painter.setRenderHint(QPainter::Antialiasing,true);

QPainterPathpath;

path.moveTo(80,320);

path.cubicTo(200,80,320,80,480,320);

painter.setPen(QPen(Qt::black,8));

painter.drawPath(path);



TheQPainterPathclasscanspecifyarbitraryvectorshapesby

connectingbasicgraphicalelementstogether:straightlines,

ellipses,polygons,arcs,quadraticandcubicBéziercurves,and

otherpainterpaths.Painterpathsaretheultimatedrawing



primitiveinthesensethatanyshapeorcombinationofshapes

canbeexpressedasapath.

Apathspecifiesanoutline,andtheareadescribedbythe

outlinecanbefilledusingabrush.IntheexampleofFigure8.5

(c),wedidn'tsetabrush,soonlytheoutlineisdrawn.

Thethreeexamplesaboveusebuilt-inbrushpatterns

(Qt::SolidPattern,Qt::DiagCrossPattern,andQt::NoBrush).Inmodern

applications,gradientfillsareapopularalternativeto

monochromefillpatterns.Gradientsrelyoncolorinterpolation

toobtainsmoothtransitionsbetweentwoormorecolors.They

arefrequentlyusedtoproduce3Deffects;forexample,the

PlastiquestyleusesgradientstorenderQPushButtons.

Qtsupportsthreetypesofgradients:linear,conical,andradial.

TheOvenTimerexampleinthenextsectioncombinesallthree

typesofgradientsinasinglewidgettomakeitlooklikethereal

thing.

Lineargradientsaredefinedbytwocontrolpointsandbya

seriesof"colorstops"onthelinethatconnectsthesetwo

points.Forexample,thelineargradientofFigure8.6is

createdusingthefollowingcode:

QLinearGradientgradient(50,100,300,350);

gradient.setColorAt(0.0,Qt::white);

gradient.setColorAt(0.2,Qt::green);

gradient.setColorAt(1.0,Qt::black);



Figure8.6.QPainter'sgradientbrushes



[Viewfullsizeimage]



Wespecifythreecolorsatthreedifferentpositionsbetween

thetwocontrolpoints.Positionsarespecifiedasfloatingpointvaluesbetween0and1,where0correspondstothe

firstcontrolpointand1tothesecondcontrolpoint.Colors

betweenthespecifiedstopsareinterpolated.

Radialgradientsaredefinedbyacenterpoint(xc,yc),a

radiusr,andafocalpoint(xf,yf),inadditiontothecolor

stops.Thecenterpointandtheradiusspecifyacircle.The

colorsspreadoutwardfromthefocalpoint,whichcanbe

thecenterpointoranyotherpointinsidethecircle.

Conicalgradientsaredefinedbyacenterpoint(xc,yc)and

anangle .Thecolorsspreadaroundthecenterpointlike

thesweepofawatch'ssecondshand.

SofarwehavementionedQPainter'spen,brush,andfont

settings.Inadditiontothese,QPainterhasothersettingsthat

influencethewayshapesandtextaredrawn:



Thebackgroundbrushisusedtofillthebackgroundof

geometricshapes(underneaththebrushpattern),text,or

bitmapswhenthebackgroundmodeisQt::OpaqueMode(the

defaultisQt::transparentMode).

Thebrushoriginisthestartingpointforbrushpatterns,

normallythetop-leftcornerofthewidget.

Theclipregionistheareaofthedevicethatcanbepainted.

Paintingoutsidetheclipregionhasnoeffect.

Theviewport,window,andworldmatrixdeterminehow

logicalQPaintercoordinatesmaptophysicalpaintdevice

coordinates.Bydefault,thesearesetupsothatthelogical

andphysicalcoordinatesystemscoincide.Coordinate

systemsarecoveredinthenextsection.

Thecompositionmodespecifieshowthenewlydrawnpixels

shouldinteractwiththepixelsalreadypresentonthepaint

device.Thedefaultis"sourceover",wheredrawnpixelsare

drawnontopofexistingpixels.Thisissupportedonlyon

certaindevicesandiscoveredlaterinthischapter.

Atanytime,wecansavethecurrentstateofapainteronan

internalstackbycallingsave()andrestoreitlateronbycalling

restore().Thiscanbeusefulifwewanttotemporarilychange

somepaintersettingsandthenresetthemtotheirprevious

values,aswewillseeinthenextsection.







PainterTransformations

WithQPainter'sdefaultcoordinatesystem,thepoint(0,0)is

locatedatthetop-leftcornerofthepaintdevice;xcoordinates

increaserightwardandycoordinatesincreasedownward.Each

pixeloccupiesanareaofsize1x1inthedefaultcoordinate

system.

Oneimportantthingtounderstandisthatthecenterofapixel

lieson"half-pixel"coordinates.Forexample,thetop-leftpixel

coverstheareabetweenpoints(0,0)and(1,1),anditscenter

islocatedat(0.5,0.5).IfweaskQPaintertodrawapixelat,say,

(100,100),itwillapproximatetheresultbyshiftingthe

coordinateby+0.5inbothdirections,resultinginthepixel

centeredat(100.5,100.5)beingdrawn.

Thisdistinctionmayseemratheracademicatfirst,butithas

importantconsequencesinpractice.First,theshiftingby+0.5

onlyoccursifantialiasingisdisabled(thedefault);if

antialiasingisenabledandwetrytodrawapixelat(100,100)

inblack,QPainterwillactuallycolorthefourpixels(99.5,99.5),

(99.5,100.5),(100.5,99.5),and(100.5,100.5)lightgray,to

givetheimpressionofapixellyingexactlyatthemeetingpoint

ofthefourpixels.Ifthiseffectisundesirable,wecanavoiditby

specifyinghalf-pixelcoordinates,forexample,(100.5,100.5).

Whendrawingshapessuchaslines,rectangles,andellipses,

similarrulesapply.Figure8.7showshowtheresultofa

drawRect(2,2,6,5)callvariesaccordingtothepen'swidth,when

antialiasingisoff.Inparticular,itisimportanttonoticethata6

x5rectangledrawnwithapenwidthof1effectivelycoversan

areaofsize7x6.Thisisdifferentfromoldertoolkits,including

earlierversionsofQt,butitisessentialformakingtruly

scalable,resolution-independentvectorgraphicspossible.



Figure8.7.Drawinga6x5rectanglewithno

antialiasing



Nowthatweunderstandthedefaultcoordinatesystem,wecan

takeacloserlookathowitcanbechangedusingQPainter's

viewport,window,andworldmatrix.(Inthiscontext,theterm

"window"doesnotrefertoawindowinthesenseofatop-level

widget,andthe"viewport"hasnothingtodowithQScrollArea's

viewport.)

Theviewportandthewindowaretightlybound.Theviewportis

anarbitraryrectanglespecifiedinphysicalcoordinates.The

windowspecifiesthesamerectangle,butinlogicalcoordinates.

Whenwedothepainting,wespecifypointsinlogical

coordinates,andthosecoordinatesareconvertedintophysical

coordinatesinalinearalgebraicmanner,basedonthecurrent

windowviewportsettings.

Bydefault,theviewportandthewindowaresettothedevice's

rectangle.Forexample,ifthedeviceisa320x200widget,

boththeviewportandthewindowarethesame320x200

rectanglewithitstop-leftcorneratposition(0,0).Inthiscase,

thelogicalandphysicalcoordinatesystemsarethesame.

Thewindowviewportmechanismisusefultomakethedrawing

codeindependentofthesizeorresolutionofthepaintdevice.

Forexample,ifwewantthelogicalcoordinatestoextendfrom

(-50,-50)to(+50,+50),with(0,0)inthemiddle,wecanset



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 8. 2D and 3D Graphics

Tải bản đầy đủ ngay(0 tr)

×