89
CS378 - Mobile Computing 2D Graphics A Crash Course in Using (Android) 2D Graphics Libraries

CS378 - Mobile Computing

  • Upload
    ziven

  • View
    55

  • Download
    0

Embed Size (px)

DESCRIPTION

CS378 - Mobile Computing. 2D Graphics A Crash Course in Using (Android) 2D Graphics Libraries. 2D Graphics Crash Course. Render Heating animal remains to extract fat OR generating an image from a (mathematical) model. Using Graphics. Not an end in itself - PowerPoint PPT Presentation

Citation preview

CS378 - Mobile Computing

CS378 - Mobile Computing2D GraphicsA Crash Course in Using (Android) 2D Graphics Libraries2D Graphics Crash CourseRenderHeating animal remains to extract fatORgenerating an image from a (mathematical) model

2

Using GraphicsNot an end in itselfCreate a richer, easier to use UIDisplay information in a easier to understand way3

Richer UIThe Apple Effect?4

Visual Display of InformationEdward TufteYale professor (poly sci, stats, and cs)spark linessmall multiplecritical of PowerPoint

5

graphical displays of information6Joseph Minard Napoleon's Invasion of RussiaLocation, size of army, data, temperature7

John Snow - Deaths from Cholera, 1854 Broad Street Outbreak (The Ghost Map)8

Space Debris Plot9

Visualizing DataBen Fry, one of the creators of Processing10

All Roads11

Files on Disk - WinDirStats12

S&P 500 Heat Map13

CS324E Heat Map14

CS324E Wator World15

Image Processing16

Color Histogram17

Histogram Equalization18

Revised Image19

20

20

Android GraphicsNOT the Java awt or swing packagescustom set of classesCanvas: class that holds code for various "draw" methodsSimilar to Java Graphics, Graphics2D objectsPaint: Controls the drawing. A whole host of properties. Bitmap: the things drawn onDrawable: the thing to draw. (rectangles, images, lines, etc.)

21Two Methods for Displaying 2D GraphicsTwo approachesdraw graphics or animations into a View object that is part of layoutdefine graphics that go into Viewsimple approach for non dynamic graphics or simple "tweened" animationsDraw graphics directly to a Canvasthe complex way, but with more control

22

Simple GraphicsUse Drawables in ViewsCreate a folder res/drawableAdd imagespng (preferred)jpg (acceptable)gif (discouraged)

Images can be added as background for Views23

Simple GraphicsChange background to an imagepreviously used background colors24Top Ten With Image Background25

Add ImageView to LayoutIn the main.xml for top ten

26

ImageView AttributesscaleType: how image should be moved or resized in the ImageViewtint: affects color of imagemore to position image in ImageView

27

Changing ImageView ProgrammaticallyRandomly set the alpha (transparency of the image)Or pick an image randomlyOr set image based on month (Season)

28

28Using a CanvasSimple way -> Create a custom View and override the onDraw methodThe Canvas is a parameter to onDrawCreate a class that extends Viewoverride the 2 parameter constructoroverride the onDraw methodperform custom drawing in the onDraw methodadd the View to the proper layout29Requesting Redraws of a Viewcall invalidate() on a View to redraw itinvalidate redraws the whole Viewpossible to redraw only a portion of the View, the part that changedseveral overloaded versions of invalidate that accept a region of the Viewonly that portion redrawnOverride the onDraw method for the View to redrawfor really complex drawing and graphics move drawing off of the UI thread to a SurfaceView (more complex)30Simple Graphics ExampleAdd CustomView to XMLin main.xmladd custom View as element in LinearLayout31

Simple Example - Graphics View32

GraphicsView - onDraw33

Simple Graphics Result34

GuessFourBoard drawn in onDraw method of a ViewBoard will resize for different deviceslines, ovals, rectangles, and texts35

Painttypically create Paint with anti aliasingPaint p = new Paint(Paint.ANTI_ALIAS_FLAG);36

Anti Aliasing37

37Using the Canvas Classmethods to draw:rectangleslinesarcspathsimagescirclesovalspointstextand a few I missed

Ability to set the "clip", portion of canvas where drawing takes placecommands to draw something that is outside clip are ignoredAbility to translate, rotate, and scale the canvas

38Paint Objectmany, many attributes and properties including:current color to draw withwhether to fill or outline shapessize of stroke when drawingtext attributes including size, style (e.g. underline, bold), alignment, gradients

39Gradients3 kinds of gradientsLinearGradeintRadialGradeintSweepGradientat least 2 color, but possibly moreflows from one color to another

40Linear Gradient41

LinearGradient42

RadialGradient43

43RadialGradient44

RadialGradeintadd depth to pegs and open spots in Guess Four game45

SweepGradient46

SweepGradient47

SweepGradient48

SweepGradient49

SweepGradient50

Animation51Simple AnimationAnimation altering some property of a 2D primitivepositionsizecoloralphaSimplest animation loop, after onDraw, call invalidateat the mercy of the UI frame rate52

Simple (And Poor) Animation Approachdraw as fast as possibleemulator frame rate (on my machine) 12 fpsdev device frame rate, high 50s fps53

Better Animation LoopCreate a Handler to delay / sleepupdate method will call sleep method on the Handler54update methodanimation loopupdate tells handler to sleep handler calls update when it wakes up 55

tweened AnimationS56Simple AnimationsTweened Animationsalso know as View Animationsprovide a way to perform simple animations on Views, Bitmaps, TextViews, Drawablesprovide start point, end point, size, rotation, transparency, other propertiesCan set up tweened animation in XML or programmatically57Tweened AnimationsUsed to alter one of four properties of a single Drawable resourceBitmap graphic (image), shape, TextView, any View (background)Tweened animations can affectAlpha (transparency / opaqueness)RotationScale (size)Location (movement, Translate)

58Tweened Animationsdefine interpolator in XML (optional)allow animation to be repeated, accelerate, decelerate, "bounce", and morecan use built in interpolators or create your owndefine animation in XMLalpha, rotate, scale, translatedefine from value, to value, and durationIn program load and start animation in response to some eventGuess Four, invalid choice, solved puzzle

59Guess Four res/animshake up down

shake left right60

GuessFour res/animcycle_7.xml

spin.xml

61

GuessFour ExampleOn error board shakes back and forthOn win board spinsFrom BoardView in GuessFour62

More Tweened Exampleshyperspace example from android dev siterotate and change alphaanimation types:alphascaletranslaterotate63http://developer.android.com/guide/topics/resources/animation-resource.html

More Tweened ExamplesMoving ButtonNote, tweened animations draw the button in a different spotBut, the button's location is not really changed64

Up and Down Animation65

Moving Button Activity66

Use extra from Intent to determine what type of animation to perform.Tweened Animation67

Change Background ColorCalled when button clickedonClick attribute68

Result?property animations

-Available POST GINgerbread 69Property AnimationsA more general animation frameworkTweened Animations can only affect alpha, scale, rotation, and positionProperty Animations can affect any property of an objecttypically a View or Drawablecan be defined in sets, change multiple properties at a timeanimation created separate from target object, reuse with different objects

70http://developer.android.com/guide/topics/graphics/prop-animation.htmlProperty Animation - ClassesValueAnimatorbase class for property animationsObject Animatorconvenience class for animating specific object and propertyViewPropertyAnimatoroptimized, simple animation of View objectsevaluator classes such as ArgbEvaluator to animate property by defining how it changes over time71Property AnimationObject animationfrom moving button example

animated class must have a "set method

72

rendering with complex calculations73More Complex GraphicsDon't want apps to become unresponsiveIf complex graphics or animation use SurfaceView classMain view not waiting on onDraw to finishsecondary thread with reference to SurfaceViewSrufaceView draws and when done display result

74Using a SurfaceViewextend SurfaceView implement SurfaceHolder.Callbackmethods to notify main View when SurfaceView is created, changed or destroyed

75Simple ExampleStatic Screencontinuously draw several hundred small rectangles (points, with stroke = 10)slowly fill screen and then keep changing76

Implement SurfaceHolder.Callback methods77

Prevent Runaway Threads!78

Inner Class for Thread79

Run Method in StaticThread80Standard Approach for Drawing on SurfaceViewDemo run()Pronounced flicker and jitterDouble buffer under the hoodWe are drawing on two different BitmapsCanvas does drawing onto Bitmap81

Remove Flicker / JitterIf we draw background each "frame" then we don't redraw previous rectanglesHow about "saving" all the data?points, colors

82

AlternativeRecall two approaches:draw on UI thread by overriding onDrawcreate custom View (tutorial 4)okay if not a lot of drawingmust keep UI thread responsivecomplex drawing or animations using SurfaceViewThird approach, possible variation on the above two approachesmaintain a separate Bitmap

83Separate BitmapStaticThread has a Bitmap instance varInitialize in constructor84

Updates to Bitmap85

Create a Canvas todraw on the Bitmap we are savingWhen donedrawing toBitmap useSurfaceViewCanvas todrawDemo Alt Version of run()Flicker and jitter?Also possible to save Bitmap to file for later use86

AnimationsFrame based vs. Time basedFrame based:update every framesimple, but difference in frame ratesTime basedupdate every frame but based on time elapsed since last framemore work, more accuratesdk example lunar lander87

Checking Frame RateFrom StaticViewEmulator 6-7 fps, dev phone 40 -45 fps88

Controlling Frame RateSleep after completing work in loop of runMore complex than shown, use previous time and current time89