-->
Feb 09, 2018 When an app needs to, or is forced to use the GPU, it means your PC is consuming more power. Normally, your system decides for itself which app should use the dedicated GPU but you can of course force it. Windows 10 is adding a new panel that lets you set graphics performance per app.
Android provides a very rich and diverse framework for supporting 2D graphics and animations. This topic introduces these frameworks and discusses how to create custom graphics and animations for use in a Xamarin.Android application.
Overview
Despite running on devices that are traditionally of limited power, thehighest rated mobile applications often have a sophisticated UserExperience (UX), complete with high quality graphics and animationsthat provide an intuitive, responsive, dynamic feel. As mobileapplications get more and more sophisticated, users have begun toexpect more and more from applications.
Luckily for us, modern mobile platforms have very powerful frameworksfor creating sophisticated animations and custom graphics whileretaining ease of use. This enables developers to add richinteractivity with very little effort.
UI API frameworks in Android can roughly be split into two categories:Graphics and Animation.
Graphics are further split into different approaches for doing 2D and3D graphics. 3D graphics are available via a number of built inframeworks such as OpenGL ES (a mobile specific version of OpenGL), andthird-party frameworks such as MonoGame (a cross platform toolkitcompatible with the XNA toolkit). Although 3D graphics are not withinthe scope of this article, we will examine the built-in 2D drawingtechniques.
Android provides two different API's for creating 2D graphics. One is ahigh level declarative approach and the other a programmatic low-levelAPI:
Drawable Resources – These are used to create custom graphicseither programmatically or (more typically) by embedding drawinginstructions in XML files. Drawable resources are typically definedas XML files that contain instructions or actions for Android torender a 2D graphic.
Canvas – this is a low level API that involves drawingdirectly on an underlying bitmap. It provides very fine-grainedcontrol over what is displayed.
Microsoft Graphics Software
In addition to these 2D graphics techniques, Android also providesseveral different ways to create animations:
Drawable Animations – Android also supportsframe-by-frame animations known as Drawable Animation. This isthe simplest animation API. Android sequentially loads and displaysDrawable resources in sequence (much like a cartoon).
View Animations – View Animations are the originalanimation API's in Android and are available in all versions ofAndroid. This API is limited in that it will only work with Viewobjects and can only perform simple transformations on those Views.View animations are typically defined in XML files found in the
/Resources/anim
folder.Property Animations – Android 3.0 introduced a new set ofanimation API's known as Property Animations. These new API'sintroduced an extensible and flexible system that can be used toanimate the properties of any object, not just View objects. Thisflexibility allows animations to be encapsulated in distinctclasses that will make code sharing easier.
View Animations are more suitable for applications that must supportthe older pre-Android 3.0 API's (API level 11). Otherwise applicationsshould use the newer Property Animation API's for the reasons that werementioned above.
All of these frameworks are viable options, however where possible,preference should be given to Property Animations, as it is a moreflexible API to work with. Property Animations allow for animationlogic to be encapsulated in distinct classes that makes code sharingeasier and simplifies code maintenance.
Accessibility
Graphics and animations help to make Android apps attractive and fun touse; however, it is important to remember that some interactions occurvia screenreaders, alternate input devices, or with assisted zoom.Also, some interactions may occur without audio capabilities.
Apps are more usable in these situations if they have been designedwith accessibility in mind: providing hints and navigation assistancein the user-interface, and ensuring there is text-content ordescriptions for pictorial elements of the UI.
Refer toGoogle's Accessibility Guide formore information on how to utilize Android's accessibility APIs.
2D Graphics
Drawable Resources are a popular technique in Android applications. Aswith other resources, Drawable Resources are declarative –they're defined in XML files. This approach allows for a cleanseparation of code from resources. This can simplify development andmaintenance because it is not necessary to change code to update orchange the graphics in an Android application. However, while DrawableResources are useful for many simple and common graphic requirements,they lack the power and control of the Canvas API.
The other technique, using theCanvas object, is very similar toother traditional API frameworks such as System.Drawing or iOS's CoreDrawing. Using the Canvas object provides the most control of how 2Dgraphics are created. It is appropriate for situations where a DrawableResource will not work or will be difficult to work with. For example,it may be necessary to draw a custom slider control whose appearancewill change based on calculations related to the value of the slider.
Let's examine Drawable Resources first. They are simpler and cover themost common custom drawing cases.
Drawable Resources
Drawable Resources are defined in an XML file in the directory/Resources/drawable
. Unlike embedding PNG or JPEG's, it is notnecessary to provide density-specific versions of Drawable Resources.At runtime, an Android application will load these resources and usethe instructions contained in these XML files to create 2D graphics.Android defines several different types of Drawable Resources:
ShapeDrawable– This is a Drawable object that draws a primitive geometric shapeand applies a limited set of graphical effects on that shape. Theyare very useful for things such as customizing Buttons or settingthe background of TextViews. We will see an example of how to use a
ShapeDrawable
later in this article.StateListDrawable– This is a Drawable Resource that will change appearance based onthe state of a widget/control. For example, a button may change itsappearance depending on whether it is pressed or not.
LayerDrawable– This Drawable Resource that will stack several other drawables oneon top of another. An example of a LayerDrawable is shown in thefollowing screenshot:
TransitionDrawable– This is a LayerDrawable but with one difference. ATransitionDrawable is able to animate one layer showing up overtop another.
LevelListDrawable– This is very similar to a StateListDrawable in that it willdisplay an image based on certain conditions. However, unlike aStateListDrawable, the LevelListDrawable displays an imagebased on an integer value. An example of a LevelListDrawablewould be to display the strength of a WiFi signal. As the strengthof the WiFi signal changes, the drawable that is displayed willchange accordingly.
ScaleDrawable/ClipDrawable– As their name implies, these Drawables provide both scaling andclipping functionality. The ScaleDrawable will scale anotherDrawable, while the ClipDrawable will clip another Drawable.
InsetDrawable– This Drawable will apply insets on the sides of another Drawableresource. It is used when a View needs a background that is smallerthan the View's actual bounds.
XML BitmapDrawable– This file is a set of instructions, in XML, that are to beperformed on an actual bitmap. Some actions that Android canperform are tiling, dithering, and anti-aliasing. One of the verycommon uses of this is to tile a bitmap across the background of alayout.
Drawable Example
Let's look at a quick example of how to create a 2D graphic using aShapeDrawable
. A ShapeDrawable
can define one of the four basic shapes:rectangle, oval, line, and ring. It is also possible to apply basiceffects, such as gradient, colour, and size. The following XML is aShapeDrawable
that may be found in the AnimationsDemo companionproject (in the file Resources/drawable/shape_rounded_blue_rect.xml
).It defines a rectangle with a purple gradient background and roundedcorners:
We can reference this Drawable Resource declaratively in a Layout orother Drawable as shown in the following XML:
Drawable Resources can also be applied programmatically. The followingcode snippet shows how to programmatically set the background of aTextView:
To see what this would look like, run the AnimationsDemo project andselect the Shape Drawable item from the main menu. We should seesomething similar to the following screenshot:
For more details about the XML elements and syntax of DrawableResources, consultGoogle's documentation.
Using the Canvas Drawing API
Drawables are powerful but have their limitations. Certain things areeither not possible or very complex (for example: applying a filter toa picture that was taken by a camera on the device). It would be verydifficult to apply red-eye reduction by using a Drawable Resource.Instead, the Canvas API allows an application to have very fine-grainedcontrol to selectively change colors in a specific part of the picture.
One class that is commonly used with the Canvas is thePaint class. This class holdscolour and style information about how to draw. It is used to providethings such a color and transparency.
The Canvas API uses the painter's model to draw 2D graphics.Operations are applied in successive layers on top of each other. Eachoperation will cover some area of the underlying bitmap. When the areaoverlaps a previously painted area, the new paint will partially orcompletely obscure the old. This is the same way that many otherdrawing APIs such as System.Drawing and iOS's Core Graphics work.
There are two ways to obtain a Canvas
object. The first way involvesdefining a Bitmap object, and theninstantiating a Canvas
object with it. For example, the followingcode snippet creates a new canvas with an underlying bitmap:
The other way to obtain a Canvas
object is by theOnDraw callback method thatis provided theView base class. Android calls thismethod when it decides a View needs to draw itself and passes in aCanvas
object for the View to work with.
The Canvas class exposes methods to programmatically provide the drawinstructions. For example:
Canvas.DrawPaint– Fills the entire canvas's bitmap with the specified paint.
Canvas.DrawPath– Draws the specified geometric shape using the specifiedpaint.
Canvas.DrawText– Draws the text on the canvas with the specified colour. Thetext is drawn at location
x,y
.
Drawing with the Canvas API
Let's see an example of the Canvas API in action. The following codesnippet shows how to draw a view:
This code above first creates a red paint and a green paint object. Itfills the content of the canvas with red, and then instructs the canvasto draw a green rectangle that is 25% of the width of the canvas. Anexample of this can be seen by in AnimationsDemo
project that isincluded with the source code for this article. By starting up theapplication and selecting the Drawing item from the main menu, weshould a screen similar to the following:
Animation
Users like things that move in their applications. Animations are agreat way to improve the user experience of an application and help itstand out. The best animations are the ones that users don't noticebecause they feel natural. Android provides the following three API'sfor animations:
View Animation – This is the original API. Theseanimations are tied to a specific View and can perform simpletransformations on the contents of the View. Because of it'ssimplicity, this API still useful for things like alpha animations,rotations, and so forth.
Property Animation – Property animations were introducedin Android 3.0. They enable an application to animate almostanything. Property animations can be used to change any property ofany object, even if that object is not visible on the screen.
Drawable Animation – This a special Drawable resourcethat is used to apply a very simple animation effect to layouts.
In general, property animation is the preferred system to use as it ismore flexible and offers more features.
View Animations
View animations are limited to Views and can only perform animations onvalues such as start and end points, size, rotation, and transparency.These types of animations are typically referred to as tweenanimations. View animations can be defined two ways –programmatically in code or by using XML files. XML files are thepreferred way to declare view animations, as they are more readable andeasier to maintain.
The animation XML files will be stored in the /Resources/anim
directory of a Xamarin.Android project. This file must have one of thefollowing elements as the root element :
alpha
– A fade-in or fade-out animation.rotate
– A rotation animation.scale
– A resizing animation.translate
– A horizontal and/or vertical motion.set
– A container that may hold one or more of the otheranimation elements.
By default, all animations in an XML file will be appliedsimultaneously. To make animations occur sequentially, set theandroid:startOffset
attribute on one of the elements defined above.
It is possible to affect the rate of change in an animation by using aninterpolator. An interpolator makes it possible for animation effectsto be accelerated, repeated, or decelerated. The Android frameworkprovides several interpolators out of the box, such as (but not limitedto):
AccelerateInterpolator
/DecelerateInterpolator
– theseinterpolators increase or decrease the rate of change in ananimation.BounceInterpolator
– the change bounces at the end.LinearInterpolator
– the rate of changes is constant.
The following XML shows an example of an animation file that combinessome of these elements:
This animation will perform all of the animations simultaneously. Thefirst scale animation will stretch the image horizontally and shrink itvertically, and then the image will simultaneously be rotated 45degrees counter-clockwise and shrink, disappearing from the screen.
The animation can be programmatically applied to a View by inflatingthe animation and then applying it to a View. Android provides thehelper class Android.Views.Animations.AnimationUtils
that willinflate an animation resource and return an instance ofAndroid.Views.Animations.Animation
. This object is applied to a Viewby calling StartAnimation
and passing the Animation
object. Thefollowing code snippet shows an example of this:
Now that we have a fundamental understanding of how View Animationswork, lets move to Property Animations.
Property Animations
Property animators are a new API that was introduced in Android 3.0.They provide a more extensible API that can be used to animate anyproperty on any object.
All property animations are created by instances of theAnimatorsubclass. Applications do not directly use this class, instead they useone of it's subclasses:
ValueAnimator –This class is the most important class in the entire propertyanimation API. It calculates the values of properties that need tobe changed. The
ViewAnimator
does not directly update thosevalues; instead, it raises events that can be used to updateanimated objects.ObjectAnimator– This class is a subclass of
ValueAnimator
. It is meantto simplify the process of animating objects by accepting a targetobject and property to update.AnimationSet– This class is responsible for orchestrating how animationsrun in relation to one another. Animations may run simultaneously,sequentially, or with a specified delay between them.
Evaluators are special classes that are used by animators tocalculate the new values during an animation. Out of the box, Androidprovides the following evaluators:
IntEvaluator– Calculates values for integer properties.
FloatEvaluator– Calculates values for float properties.
ArgbEvaluator– Calculates values for colour properties.
If the property that is being animated is not a float
, int
orcolour, applications may create their own evaluator by implementing theITypeEvaluator
interface. (Implementing custom evaluators is beyondthe scope of this topic.)
Using the ValueAnimator
There are two parts to any animation: calculating animated values andthen setting those values on properties on some object.ValueAnimatorwill only calculate the values, but it will not operate on objectsdirectly. Instead, objects will be updated inside event handlers thatwill be invoked during the animation lifespan. This design allowsseveral properties to be updated from one animated value.
You obtain an instance of ValueAnimator
by calling one of thefollowing factory methods:
ValueAnimator.OfInt
ValueAnimator.OfFloat
ValueAnimator.OfObject
Once that is done, the ValueAnimator
instance must have its durationset, and then it can be started. The following example shows how toanimate a value from 0 to 1 over the span of 1000 milliseconds:
But itself, the code snippet above is not very useful – theanimator will run but there is no target for the updated value. TheAnimator
class will raise the Update event when it decides that it isnecessary to inform listeners of a new value. Applications may providean event handler to respond to this event as shown in the followingcode snippet:
Now that we have an understanding of ValueAnimator
, lets learn moreabout the ObjectAnimator
.
Using the ObjectAnimator
ObjectAnimator is asubclass of ViewAnimator
that combines the timing engine and valuecomputation of the ValueAnimator
with the logic required to wire upevent handlers. The ValueAnimator
requires applications to explicitlywire up an event handler – ObjectAnimator
will take care ofthis step for us.
Microsoft Graphics App Store
The API for ObjectAnimator
is very similar to the API forViewAnimator
, but requires that you provide the object and the nameof the property to update. The following example shows an exampleof using ObjectAnimator
:
As you can see from the previous code snippet, ObjectAnimator
canreduce and simplify the code that is necessary to animate an object.
Drawable Animations
The final animation API is the Drawable Animation API. Drawableanimations load a series of Drawable resources one after the other anddisplay them sequentially, similar to a flip-it cartoon.
Drawable resources are defined in an XML file that has an<animation-list>
element as the root element and a series of <item>
elements that define each frame in the animation. This XML file isstored in the /Resource/drawable
folder of the application. Thefollowing XML is an example of a drawable animation:
This animation will run through six frames. The android:duration
attribute declares how long each frame will be displayed. The next codesnippet shows an example of creating a Drawable animation and startingit when the user clicks a button on the screen:
At this point we have covered the foundations of the animation APIsavailable in an Android application.
Summary
This article introduced a lot of new concepts and API's to help addsome graphics to an Android application. First it discussed the various2D graphics API's and demonstrated how Android allows applications todraw directly to the screen using a Canvas object. We also saw somealternate techniques that allow graphics to be declarativelycreated using XML files. Then we went on to discuss the old and newAPI's for creating animations in Android.
Related Links
-->Windows provides APIs and components that support graphics, gaming, and imaging.
In this section
Topic | Description |
---|---|
DirectX Graphics and Gaming | DirectX graphics provides a set of APIs that you can use to create games and other high-performance multimedia applications. |
DirectComposition | DirectComposition enables high-performance bitmap composition with transforms, effects, and animations. You can use the DirectComposition API to create visually engaging user interfaces that feature rich and fluid animated transitions from one visual to another. |
Game Mode | The Game Mode APIs for the Universal Windows Platform (UWP) allow you to produce the most optimized gaming experience by taking advantage of Game Mode in Windows 10. |
Gaming Device Information | The Gaming Device Information APIs allow UWP game developers to determine the type of console the game is running on, in order to make run-time choices on how to best use the hardware. |
TruePlay | The TruePlay APIs for UWP provide developers with a new set of tools to combat cheating within their PC games. |
Windows Imaging Component (WIC) | The Windows Imaging Component (WIC) is an extensible platform that provides low-level API for digital images. WIC supports the standard web image formats, high dynamic range images, and raw camera data. |
Win2D (External Site) | Win2D is an easy-to-use Windows Runtime API for immediate mode 2D graphics rendering with GPU acceleration. It is available to C# and C++ developers writing Windows apps for Windows 8.1, Windows Phone 8.1 and Windows 10. It utilizes the power of Direct2D, and integrates seamlessly with XAML and CoreWindow. |
ANGLE for Windows Store (External Site) | ANGLE for Windows Store is an open-source project that allows developers to run OpenGL ES content on Windows by translating OpenGL ES API calls to DirectX 11 API calls. ANGLE for Windows Store supports Windows 8.1, Windows Phone 8.1, and Windows 10. |