Prezentace na téma: "Windows Presentation Foundation Přehled technologií, díl III."— Transkript prezentace:
1Windows Presentation Foundation Přehled technologií, díl III. Dalibor Kačmář Academic Developer Evangelist Microsoft s.r.o.
2Agenda WPF díl I. WPF díl II. WPF díl III. Přehled WPF Layout aplikace Architektura aplikaceÚvod do XAMLLayout aplikaceOvládací prvkyWPF díl II.Data bindingStyly, šablonyResourcesWPF díl III.Novinky v grafice2D grafika3D grafikaAnimace
3Novinky v grafice Silná podpora grafiky ve WPF Je plně integrována do programového modeluMůže být součástí libovolné části UIGrafické tvary jsou uspořádány do stromu elementů uživatelského rozhranníOdpadá nutnost neustále překreslovat oknaSložitě manipulovat s vykreslenou grafikouWPF se za nás postará o překreslováníVšechny elementy jsou vektorové, nikoli bitové mapy, tedy nezávislé na rozlišení!
4Společné novinky v grafice Grafika nezávislá na rozlišení a zařízeníPostavena na Device Independent PixelVylepšená přesnostSouřadnicový systém WPF a transformace používají double místo float typuWPF poskytuje širší barevný gamut (scRGB)Pokročilá podpora grafiky a animacíHit testování, minimální překreslování, integrace animaceHardwarová akcelerace
5WPF grafické API Grafické objekty 3D Grafické objekty Pera a štětce Tvary (Shapes) - 2D primitivyGeometrické entity (Geometries)Zobrazení (Drawings)– Geometické entity, bitové mapy, texty, skupinyTransformace a animaceVisuály (Visuals) – základní stavební elementy WPF vykreslovacího subsystému3D Grafické objekty3D primitivy, transformace a animace
6AgendaNovinky v grafice2D grafika3D grafikaAnimace
72D tvary Elementy UI stromu Stejné jako jiné ovládací prvky a elementy Mohou mít k sobě připojeny události, např. klik myšiRectangleEllipsePolylinePolygonPathWPF offers a set of drawing primitive elements. These can be used in your user interface tree like any other element. They are fully integrated into WPF, so they participate in layout, and work just like any other element in your UI.This means graphics can be created entirely in markup – there is no need to use code to use graphics primitives. (Although you can use code if you like.)The Path shape is particularly powerful. In fact it offers a superset of the functionality of all the other shapes – the rest are really only present for convenience. Path supports shapes made up out of any combination of Bezier curves, elliptical arcs, and straight lines. You can use any number of any of these types of line to define the outline of a shape. You can also add multiple ‘figures’ to a Path – this means a shape can have more than one outline, making it possible to define shapes with holes in.
8Příklady použití Tvary jsou přístupné z kódu v pozadí <Canvas Width="100" Height="100"><Ellipse x:Name="hlava" Fill="Yellow" Stroke="Black" StrokeThickness="7" Width="100" Height="100" /><Ellipse Fill="Black" Width="10" Height="15"Canvas.Left="28" Canvas.Top="28" />Canvas.Left="62" Canvas.Top="28" /><Path Stroke="Black" StrokeThickness="6"Data="M 30,60 Q 50,90 70,60" /></Canvas>Tvary jsou přístupné z kódu v pozadíZměna vlastnosti se automaticky projeví na obrazovce// ...kód v pozadíhlava.Width = 200;
9Transformace Jakýkoli element lze transformovat Transformace Transformace nedeformuje kvalituTransformacePředdefinovanérotace, zvětšení, zkosení, posuva obecná maticová3D ekvivalentyVliv na umístění tvaruLayoutTransformPrvek je nejdříve transformován a pak aplikován layoutRenderTransformLayout neví o transformaciAny element can have a transform applied to it. You can either apply a RenderTransform, which modifies how the element appears without changing layout behavior. Or you can specify a LayoutTransform, in which case the layout system will take the effects of the transform into account.You can apply any combination of scaling, rotation, shearing, and translation. (I.e. any affine transformation. Affine transformations are ones that preserve straight lines – points lying in a straight line before the transform will also lie in a straight line after the transform.)
10Hit Testing Definován pro všechny kreslící elementy Bere transformace v úvahuVyužívá směrování událostí (bublání)<Ellipse x:Name="hlava" Fill="Yellow" Stroke="Black" StrokeThickness="7" Width="100" Height="100"MouseLeftButtonDown="OnClick"/>Hit testing for complex visuals has traditionally required a lot of work from the developer. When you have intricate imagery made up of multiple shapes, it can be difficult to work out which item, if any, the mouse is over. This becomes particularly complex if you have chains of transformations.WPF does all the work for you. All of the drawing elements automatically support hit testing. (And if you eschew the FrameworkElement-level drawing elements, and instead drop down to the low-level drawing API, there is still support down there for making hit testing straightforward.)All elements raise events for mouse activity including button, wheel, enter, and leave. The bubbling event model makes it easy to trap events for large chunks of your visual tree in a single place, and yet still be able to work out exactly which element was hit. (Events that bubble will propagate their way from the leaves of the UI tree up to the root until they hit a handler.)As an example of how this works, consider a button with custom visuals. You can make a button any shape you like, and the hit testing works perfectly, even though the button doesn’t know much about its visuals. All it does is trap the relevant mouse events as they bubble out of its visual tree. This means that even the most complex of shapes will work in exactly the same way as the basic standard rectangular button shape.
11Kompozice Proces složení více tvarů nebo obrázků ve výsledný výstup WPF na rozdíl od Win32 podporujepřekrývání libovolných elementů (ne pouze celých oken)průhlednostpoužívá anti-aliasing na hranách tvarůaplikaci transformace před kompozicí
12Možnosti kompozice DrawingBrush VisualBrush Výplň vektorovým obrázkem Výplň UI elementemZjednodušuje některé trikyReflexe UIPoužití jako 3D texturyThe DrawingBrush is conceptually very similar to the ImageBrush, in that both allow you to fill an area with a picture. The difference with the DrawingBrush is that you don’t have to use a bitmap. You can pass in any Drawing object. For example, if you use a GeometryDrawing, you can perform all the same drawing operations as the Path shape. And you can use a DrawingGroup to bring multiple GeometryDrawing elements together. You are free to use any Brush and Pen for each individual GeometryDrawing within the drawing, so you can build up sophisticated imagery and then use it as a pen.The VisualBrush has similar capabilities to DrawingBrush – it allows an imagery, vector or bitmap, to be used as a brush. The difference is that the VisualBrush takes any UI element as its source. You can even point it at a UI element that is already in use in the application. This means you can use a VisualBrush to replicate part of the UI.This can be used for tricks such as making a reflection of part of the UI by painting it somewhere else. (This can be done in conjunction with opacity to make the reflection fade.)
13Barvy A (alfa), R, G, B kanály 32 bitů na barvu (8 na kanál) není dostatečné pro technologie jako film, velké panely s kvalitním podáním barevWPF 16b na kanálZadáváno v plovoucí řádové čárce <0;1>(dostupná 8b reprezentace celým číslem)WPF uses a high-precision color representation. Windows has traditionally used 24 bits for ‘true color’ (8 bits per channel) and 32 bits when transparency is required. This is sufficient for normal screen technology, but only just. If you perform any kind of image processing, it will tend to amplify the limitations of this representation. Also, for certain display technologies such as film, or high end flat panels, you simply need more bits of color information in order to span the dynamic range of these displays without color ‘banding’.WPF uses 16 bits for each of the Alpha (transparency), Red, Green, and Blue channels. The Color type represents each channel as a floating point number with a nominal range of 0 to 1. (0 indicates minimum brightness or completely transparent, 1 represents maximum brightness or completely opaque.)The Color type also allows values to go out of range. In some image processing scenarios, it is possible for color values to be pushed out of their normal range at one stage of processing, and for later stages to bring them back into range. If Color disallowed such values, it would have to clip color values, compromising the final results.
14Obrázky a video Podpora bitových obrázků a videa ImageMediaElementIntegrace obrázků a videa do štětceVyplnění tvarůPoužití jako textura 3D povrchuVelmi silná podpora v kóduSystem.Windows.Media.ImagingThere is support for bitmap images in both element and brush form. The Image and MediaElement types allow images and video clips to be integrated as features in your UI. These are FrameworkElements like any other – they participate in layout, data binding, event handling, transformations, and all the other things you would expect any other UI element to do.You can also incorporate both images and video into brushes, which can then be used to paint other items. This lets you use bitmaps or video to paint any shape you like. You can even paint 3D surfaces!With video, you need to use a VisualBrush in order to paint shapes with a video. Images can also use VisualBrush, but there is a special ImageBrush type, which has lower overhead than the VisualBrush.There is a considerable amount of support for working with images from code. This is a pretty large topic on its own, so we don’t have time to look at it here. The System.Windows.Media.Imaging namespace is the place to look.
15Visual-Layer programování Existují případy, kdy deklarativní popis ve stromu není vhodnýWPF poskytuje „visual-layer“ APIVykreslování entit podle potřebyMetoda OnRender vykreslí jednotlivé entityOdlišný zůstává model překreslováníAplikaceVizuálníobjektyAplikaceWPFGDI+ nebo GDI32Grafická kartaFrame buffer obrazovkyInvalidateWM_PAINTWindows
17AgendaNovinky v grafice2D grafika3D grafikaAnimace
183D grafika Přináší 3D širší audienci vývojářů Integrace – můžeme použít 3D kdekoli ve UILze použít štětce pro kreslení na 3D plocháchWPF’s 3D support provides a substantially simpler model than DirectX. Of course this comes at some cost – 3D in WPF will never be quite as fast as using DirectX. But if you don’t need to push the graphics card to its limits and want some reasonably simple 3D models in your app, WPF makes this simple to do.WPF brings 3D scenes into a 2D world – you can place 3D models into the world of 2D layout. There’s also a degree of integration in the other direction – WPF’s 3D feature can use any of the Brush types available in the 2D world.
193D ve 2D světě Layout rozumí pouze 2D Použijeme obdélníkové okno do 3D světaGridTextBlockStackPanelEven though WPF is able to exploit graphics card acceleration features designed for use in 3D, it is essentially a 2D technology. The layout mechanism deals entirely in logically rectangular entities. (Of course elements are not required to be rectangular, but they are always laid out according to their rectangular bounding box, regardless of their shape.) The composition engine that combines all the elements of the UI into a final image also operates in a two-dimensional world – it effectively draws each element in turn onto the flat surface that is the screen.The only extent to which controls, shapes, and most other framework elements understand a 3rd dimension is the ‘Z-order’ which simply determines what happens when elements overlap. (The Z order is determined by the order in which elements appear in the XAML document. The earlier an element is, the further towards the back it is.) This allows us to indicate which element should appear ‘on top’ when two elements overlap. However, it is just an ordering – the Z order does not allow us to distinguish between one object being directly behind another, and being a very long way behind another. So the coordinate system for the UI is essentially two-dimensional.In a 3D world, the X, Y, and Z position of every object is specified precisely. This means that 3D models occupy a different coordinate system from the rest of the WPF UI. This presents a problem: how do we bring these two distinct coordinate systems together?The solution employed by WPF is to use a special element, Viewport3D, which bridges the gap between the two worlds. It projects the 3D world into a 2D rectangle.Note the Viewport3D is a live view – it is able to render updates in the 3D world.StackPanelDockPanel
20Viewport3D Obsahuje a vykresluje pohled na živé 3D Layout to vidí jako další elementObsahujemodelkamerusvětloAs far as WPF’s layout and composition systems are concerned, Viewport3D is just a normal 2D element like any other, with a rectangular bounding box, and which recognizes the same layout rules as all other elements. However, the Viewport3D contains a 3D model, and renders that model into the 2D space allotted.Viewport3D derives from FrameworkElement, which is the base class of all visible elements in the WPF framework. This is what enables it to participate in normal UI layout and composition.One limitation of this design is that the 3D world that the Viewport3D looks into is isolated from the main UI. You cannot arrange for the 3D model to be rearranged as part of the 2D layout process. This means that in some respects, a Viewport3D is similar to the Image and Media elements, which allow bitmaps and video to be incorporated – these elements display content which is not a completely integrated part of the UI. However, although the 3D model cannot respond to layout, the objects that represent the 3D scene are part of the WPF framework, which means you can use animation, styling, and event triggers, so it is certainly possible to use 3D in a way that feels like an integrated part of the UI.Viewport3DFrameworkElement
21Nastavení kamery Pozice kamery Kam ukazuje Definice směru „nahoru“ OrthographicCameraPozice kameryKam ukazujeDefinice směru „nahoru“Pole pohledu (širokoúhlá/telefoto)PerspectiveCameraThe Viewport3D must contain a camera – this determines the point of view from which the scene will be rendered.You must choose your camera type. The PerspectiveCamera performs a perspective-aware projection, where distant objects will appear smaller than nearby objects of the same size. This provides the most naturalistic mapping of 3D onto a 2D image. However, you may not want perspective – for certain kinds of model, the distortion inherent in perspective is undesirable. For example, if you are rendering data as a 3D graph, you might want to avoid perspective. This will produce a less natural looking picture, but it makes it easier to see the size or height of features, which for graphs or certain kinds of diagrams may be more important.<PerspectiveCameraPosition="30,45,40"LookDirection="-2,-3,6"UpDirection="0,1,0"FieldOfView="55"/>
22Světlo AmbientLight DirectionalLight PointLight SpotLight All scenes must contain at least one light source, otherwise none of the objects will be visible. (Strictly speaking, lights are just part of the model. However, they deserve special consideration because you need them to be able to see anything.)The AmbientLight type illuminates all objects uniformly. It does not vary illumination according to position or angle. This provides an easy way of making sure everything is visible, but tends to provide a very ‘flat’ look. There is nothing in nature corresponding directly to ambient light – all light comes from some light source either directly or indirectly.DirectionalLight simulates a strong light source a long distance away, such as sunlight. Parts of an object facing the light will be more brightly illuminated than those facing away from the light. This light source takes into account the orientation of objects, but not their location.PointLight simulates a nearby light source, such as a light bulb in a room. SpotLight is similar, except it does not radiate in all directions – it projects a cone of light.One of the nice things about the fact that lights are essentially a part of the model is that you can move them around – you can animate light sources just like you can animate anything else.
23Model Obsah pohledu (Viewport3D) modelován pomocí ModelVisual3D Obsahuje strom Model3D-odvozených objektůModel3DGroup, Light, GeometryModel3D, ScreenSpaceLines3DModelování těles MeshGeometry3DJednoduchá tělesa neexistujíSvětlo počítáno po vrcholechThe Viewport3D’s child must be a ModelVisual3D. This has a Content property that contains the ‘model’ – the set of objects that define the contents of the 3D scene.The model is a tree of objects, all of which derive from Model3D. The nodes are of type Model3DGroup, and the leaves are other Model3D-derived types. Surfaces are represented as GeometryModel3D objects, lights are Light objects, and wireframes are represented as ScreenSpaceLines3D objects.A GeometryModel3D represents a surface in the model. The shape of the surface is defined by an associated Geometry object, while its surface color or texture is defined by an associated Material. As with Model3D in the model tree, an optional transform may be applied.The reason for separating out the Geometry from the GeometryModel3D is that it lets us define the actual shape just the once (as a resource) and then reuse it. We can apply a different Material with each GeometryModel3D, and also a different Transform to get the shape to appear in lots of different places with various orientations and sizes.Note that the ‘resolution’ of your model, in the sense of how densely packed are the triangles that form its surfaces, is important for lighting. Lighting calculations are performed at vertexes and then spread over the triangle. So if you draw a large rectangular surface with just a couple of triangles, specular highlights won’t look very convincing. You need to put in a lot more triangles if you want specular highlights to work well.
24Materiály – 3D štětce Definují barvu nebo texturu povrchu Štětec (SolidColorBrush nebo DrawingBrush)GeometryModel3D = geometrie + materiálMateriál určuje model odrazivosti:DiffuseMaterial – matový povrchSpecularMaterial – odrazivý povrchEmissiveMaterial – aditivní míchání povrchu a textury (visuální efekty)Materiály lze kombinovat - MaterialGroupNapř. DiffuseMaterial pro fotografii + SpecularMaterial pro odrazivý povrchAll surfaces must have a material specified in order to determine what the surface will look like. Materials are based on brushes, so any drawing effect you can achieve in 2D with a Brush can also be achieved in 3D.There are three styles of brush available, which interact with lighting in different ways. The DiffuseMaterial works as though the brush had simply been used to paint the surface with a matte finish. There will be no reflective highlights when using this brush type. Where directional light sources are used, the brightness of the surface will be determined by the angle of incidence of that light source with the surface. (So the brightness will not vary as the viewer moves around.)SpecularMaterial allows you to get a shiny-looking finish. The brightness is determined not just by the angle at which directional light hits the surface, but also the angle from which the viewer is observing. It will be brightest when these two angles are the same. (If the surface were flat, this would correspond to looking into a flat mirror at just the right angle to see the light source reflected in the mirror.)EmissiveMaterial is slightly curious. You would normally apply this to a surface that sits just above another existing surface. This is because emissive surfaces are not opaque – they modify whatever is behind them using additive blending. So an emissive surface can brighten the area of the scene that it covers. If you use a textured brush such as a DrawingBrush, then the contents of the drawing will determine the pattern with which this surface brightens whatever is behind it. This is typically used to get interesting visual effects.
25Vytvoření 3D scény, použití světla, kamery a definice povrchu elementů
26AgendaNovinky v grafice2D grafika3D grafikaAnimace
27Animace Proč? Animace kdekoli Kdekoli ≠ všude Silnější dojem z aplikacíVytváří přirozenější UIPlynulejší visuální přechodyAnimace kdekoliJakoukoli vlastnost lze animovatKdekoli ≠ všudeZvážit vhodnostZdrženlivost je na místěRealizace animací deklarativně i kódemAnimation can bring a user interface to life. It is common for parts of a user interface to respond to user input. For example, buttons look like they have been physically pressed in when you click on them; UI elements might light up or change style to indicate that they might do something interesting if clicked on. Tasteful use of animation can enhance the realism of ‘moving parts’ in a UI, and make for a smoother feeling UI.Also, animation can be used to make visual transitions easier to follow. Sudden changes are jarring to watch, and can make us lose our place in the UI. By animating transitions, life can be made easier for the user.Almost any property of any visual element can be animated. (Strictly speaking, any dependency property on any element derived from FrameworkElement can be animated.)Of course it’s important to design your animations with sensitivity to the user. Careless use of animation can have a terrible impact on the UI. Too many animations will make the UI garish and distracting; animations that are slow or which force the user to wait until the end of the animation lead to frustration. So be careful not to let them get in the way. But when animation is used intelligently, it can enhance a UI significantly.
28Deklarativní animace Popisují animačnímu systému průběh Např. změň šířku (Width) z 10 na 100 během 10 sekundZbytek proveden automatickyBez nutnosti nastavit časovačeBez nutnosti vlastního vykreslováníCode is usually not required to animate the UI – WPF supports declarative animation. You can also animate from code as well if you like, but even there, it’s a usually a matter of telling the animation system what you’d like it to do for you, and letting it get on with it. The system will take care of regularly updating the display to keep the animation running.Typ animace<DoubleAnimation From="10" To="100"Duration="0:0:10"Storyboard.TargetName="myellipse"Storyboard.TargetProperty="(Ellipse.Width)" />Parametry animaceCíl animaceAnimovaná vlastnost
29Elementy animací Storyboad Trigger Timeline Animation Koordinuje běh několika animacíTriggerSpouští animaci událostí nebo hodnotou vlastnostiTimelineDefinuje časový rozsah animaceOrganizovány hierarchicky a paralelněAnimationSpecifické pro animovanou vlastnost24 typů animacíNapř. Color/Point/Single/Double/Rect3DAnimationThere are three key concepts in the animation programming model.Triggers control when animations are launched.Elements, styles and templates can have a Triggers section. This can contain two kinds of trigger: event triggers and property triggers. Property triggers are level-based a trigger is on if the specified property matches a certain value, otherwise it is off. This level-based nature means that property triggers cannot be used for starting animations, since this requires a trigger at a particular moment in time.Event triggers are edge-based rather than level-based – an event trigger fires when its chosen event is raised, or when a property changes state.For example, you could use the Mouse.MouseEnter event to trigger a particular animation. Or you can specify a set of animations to run when a particular property-based trigger becomes true, and a second set to run when it becomes false.Timelines represent a particular stretch of time, and usually define something that happens during that time. Timelines can be composed into hierarchies, allowing multiple animations to be orchestrated.Everything inside a Storyboard element is a Timeline of some description. All element types that derive from Timeline represent some particular stretch of time. They all have a BeginTime (which in the case of nested timelines is relative to their parent’s BeginTime). All timelines have a Duration, although the Duration may be implicit – if you do not specify a timeline’s Duration, it will be determined by the end times of the children – whichever child animation finishes last, its finish time determines the parent’s implied duration.ParallelTimeline elements are used to group other animations together.Animation timelines such as DoubleAnimation or ColorAnimation indicate how the target property is to be animated.Animations describe how a particular property is to be changed by the animation system.Animation timeline must be of a type matching the target property, e.g. DoubleAnimation for a property of type Double, ColorAnimation for one of Color, etc. This describes the way in which the property should be animated.The Storyboard.TargetName indicates the element to be animated. It specifies the name of the target element – this must correspond to the x:Name attribute of an element derived from FrameworkElement. The Storyboard.TargetProperty attribute indicates the name of the property to be animated. The property must always be specified as (ElementType.PropertyName).It is possible to drill into subproperties with the path. For example, if the target element’s Fill property were set to be a SolidColorBrush, you could use a Path of “(Ellipse.Fill).(SolidColorBrush.Color)” to animate the brush color. (This is the only way to animate a brush – the Brush class does not derive from FrameworkElement, so it cannot be specified as the Storyboard.TargetName.)
31Časování animací Relativní vs absolutní From-To, To, By, From-ByAktivace více animací najednou kompozicí (i na jedné vlastnosti)Zrychlení/zpomalení vyvolává přirozený vzhledNení-li určeno, rychlost je lineárníNumerical animations provide From, To, and By properties. If you specify From and To, this indicates the absolute start and end values of the animation. The previous value of the relevant property will be ignored in this case.If you just specify To, the animation will animate from the property’s current value to the target specified by To.If you specify just By, the animation is relative – it will start from the property’s current value and add the value specified in By to form the target value. (Not all animation types have a By property – only types for which addition is defined support this. ColorAnimation does not, for example.)If you specify From and By, this indicates an absolute start position and a relative target position.You might have multiple animations applied to the same property. This is useful for multi-stage animations. If you use the By property, each animation applies from where the previous one left off. If animations overlap, then if the second is a By animation, it will simply be added to the first one.If an animation specifying From overlaps in time with another animation for the same property, the later of the two overrides the earlier one.By default, animations perform linear interpolation – they change the animated property at a constant rate over the duration of the animation. This can result in a rather unrealistic feel for certain kinds of animations.Animation timelines therefore support a soft start and/or finish to the animation. By specifying an AccelerationRatio, you can make the animation gradually ramp up to speed. This property indicates the proportion of the total duration that should be spent accelerating. For example, if you specify a value of 0.3, the animation will start at zero speed, and will ramp up to full speed over the first 30% of the duration. (The appropriate value for ‘full speed’ is calculated automatically.) You can also specify a DecelerationRatio, which indicates the proportion of the total time that should be spent slowing down to a halt at the end of the animation.Obviously the sum total of these two properties must be less than or equal to one: you cannot spend more than 100% of the time speeding up and slowing down!All timelines have a RepeatBehavior property which indicates whether the timeline should repeat, and if so for how long. A value of Forever means it should repeat indefinitely. (However, if the timeline is a child of a timeline with a specific finite duration, ‘Forever’ really just means ‘Until the parent timeline ends’.) You can specific finite repetition either by indicating how long the timeline should repeat for, or the number of repetitions. Note that in both cases this includes the first run through, so a RepeatBehavior of “1x” is effectively the default. Likewise, if you make the RepeatBehavior a duration that is the same as the animation’s behavior, this also lets the animation run just once.All timelines also have an AutoReverse property. If this is set to true, the timeline will run in reverse once it reaches the end. This doubles the effective duration of the timeline.
32Ukončení animace Po ukončení se objekt vrátí do původního stavu OpakováníForever, fixní doba, počet opakováníReverzní chodVnořená animace může doběhnout dříve než rodičFillBehavior určuje, co se staneA timeline may come to an end before its parent finishes. Or it may have no parent. In this case, the timeline enters its so-called ‘fill period’ – the time between the end of its inherent duration and the end of its parent timeline. (Or the time at which the UI closes if the timeline has no parent.)There are two behaviors a timeline can exhibit in its fill period. It can either deactivate, in which case the property will revert to the value it had before the animation started. Or it can ‘hold’ – meaning that the animation’s final value continues to apply. (And if further animations target the same property, their effects will compose as discussed earlier.) The hold behaviour is the default. To deactivate at the end of the timeline’s duration, set the FillBehavior property to Deactivate.
33„Key Frame“ animaceProfesionální animace definovány sérií klíčových pozic objektůMísto série animací, definuje tyto pozicePro hladší průběh lze použít spline funkceIf you are using animation to move some object around, you may want it to follow a more complex path than a straightforward move from one point to another. You could achieve this by stringing together a sequence of animations one after the other. However, the Key Frame Animation types provide a way of specifying a series of points at various offsets into the animation. The value will be interpolated between these.This approach is named after a common technique in conventional animation. An animated scene will typically have the most important frames drawn first – these ‘key frames’ will define the basic flow and character of the animation. Once these are defined, the remaining frames are drawn by interpolating between key frames. In WPF, you can define these key frames and let the animation system perform the interpolation for you. Note that this is somewhat different from conventional animation key frames – you do not get to provide two complete drawings, and have the system interpolate between these – you are still just modifying property values on a single scene. WPF has no built-in way of ‘morphing’ from one shape to another automatically.Key frame animations can use either linear or spline interpolation. Linear interpolation just moves values at constant speed between any two key frames. This results in rather stilted and jagged motion. Using splines lets you smooth things out a little. Splines are a little tricky to get used to – you are not simply defining a curve for an object to follow – splines are used at the level of individual properties, so you might specify a spline defining how just the X coordinate behaves! The curve defined by the spline is actually a curve in the graph representing space vs time. This allows you to control the acceleration and deceleration. (By controlling acceleration and deceleration of X and Y coordinates independently, it is possible to introduce curved motion.)
35Shrnutí Grafika dostupná deklarativně i programově Nezávislá na rozlišeníVyšší přesnost a kvalitaSnaha využít výkonný hardwareWPF nabízí jednoduchý model 3DSnadněji než s DirectX, ale s nižším výkonemNejdříve si udělejte prototypAnimace výrazně obohacují UISnadná deklarace a aktivace bez kóduJakákoli vlastnost může být animována jak ve 2D, tak 3DWPF’s resolution independence is a critical part of being ready for the future. High-resolution displays are becoming increasingly common, so the ability to adapt to this is very important. Part and parcel of this is the high precision floating point representation used for all coordinates.Moreover, WPF provides a set of graphics facilities that enable you to exploit the power of the graphics hardware while being abstracted away from the capabilities of the hardware. It will fall back to software rendering when the services your application uses are not implemented in hardware, but will exploit the hardware wherever possible, enabling you to make best use of the computer’s capabilities. As the average graphical capabilities of machines improve, your software will be ready to take advantage of this.One thing to be aware of with the WPF 3D support is that it’s important to prototype your design before committing to it, with a view to checking the performance. Certain approaches to 3D can yield poor performance. In particular, hit testing can get expensive for certain kinds of models. (Since WPF allows you to modify any part of the model in any way at any time, it can’t make all of the same performance optimizations for hit testing that 3D games are able to, so it will tend to be at a natural disadvantage.)Of course it’s currently a moving target, since only previews have shipped so far. So be prepared to revisit your feasability studies when beta 2 ships. (Most things should just get faster.)