6 - 2 - Graphics and Animation - Part 2 (12-26)

5

Click here to load reader

Transcript of 6 - 2 - Graphics and Animation - Part 2 (12-26)

Page 1: 6 - 2 - Graphics and Animation - Part 2 (12-26)

Hi.I'm Adam Porter, and this is ProgrammingMobile Applications for Android HandheldSystems.If you want to draw more complex graphicsand you want to update those graphicsfrequently, then you can do your drawingwith a canvas.Now as I said earlier, a canvas is a kindof context or mechanism for drawing toan underlying bitmap.And you can access a canvas either througha generic view object or through a specialview subclass called SurfaceView.Usually, you'll draw through a genericview when your updates are less frequent,and if you take this approach, yourapplication should create a custom viewsubclass.And then the systemwill provide the canvas to your viewthrough a call to its onDraw method.If, instead, your application needs tofrequently update itsgraphics, then you might consider drawingthrough a SurfaceView.With this approach, the applicationcreates a custom, SurfaceView subclass.And it will also create a secondary threadwithwhich drawing operations on thatSurfaceView, will be performed.At run time, the application can thenacquire its own canvas, Andtherefore, exercise more control over howand when drawingoccurs.This next example application is calledGraphicsCanvasBubble.And the idea behind this applicationis that it will draw a view and thenupdate that view.But the updates are somewhat infrequent,about every second or so.So this application has an internal threadthat wakesup once every second or so, and moves theview.And then uses a canvas as it redraws theview in its new location.Let's see that in action.So here's my device.And now, I'll start up theGraphicsCanvasBubble application.The application starts up with a bubbledrawn at a randomly selected location.And every second or so, you can see thatthe bubble is erased, movedand then redrawn in it's new location.Let's look at the source code

Page 2: 6 - 2 - Graphics and Animation - Part 2 (12-26)

for this application.So here's the GraphicsCanvasBubbleapplication open in the IDE.Now, I'll open the main activity.Here you can see that the applicationloads a bitmap from the resourcesdirectory.And then it uses that bitmap to create aninstance of a custom view class called theBubbleView.Next, the code adds the BubbleViewinstance to the layout.And then it creates and starts a newthread.And that thread goes intoa loop and on each iteration, it calls theBubbleView's move method.Now as we'll see in a second, this methodchanges the BubbleViews location.And then, returns true or false dependingon whether the BubbleViewsnew location is or is not still visible onthe display.Next the code calls the view classes postinvalidate method.This message tells android to redraw thisview and after that the threadgoes to sleep for a second before wakingup and starting the process one more time.Now I'll skip over most of the details ofhow the BubbleView moves itself.And I'll focus instead on how it getsredrawn.So when the drawing thread calls the postinvalidate method, thistells Android that the BubbleView thinksit needs to be redrawn.If so, then Android will eventually callBubbleViews onDraw method.Passing in the canvas, with which theBubbleView is drawn.Let's look at that method.And as you can see, this method takes thecanvas passed into it and callsits DrawBitmap method, passing in thebitmap to draw.Passing in the top and left coordinates ofthe position at which to draw the bit map.And finally, passing in a paint objectthat defines style parametersfor this drawing operation.Now, if we'd like to really increase thefrequency.With which we're redrawing the bubble tomake it more smoothly glide across thedisplay.Then, we might want to use a canvas and aSurfaceView in order to do that.And as I mentioned earlier, SurfaceViewsneed a

Page 3: 6 - 2 - Graphics and Animation - Part 2 (12-26)

separate, non-UI thread in which to dotheir work.So that SurfaceView operationswon't interfere with UI thread operations.So, let's talk more about the SurfaceViewclass.A SurfaceView manages a low-level drawingarea called a Surface.And this Surface is a dedicated drawingarea, that is positioned within theapplications view hierarchy.To define a SurfaceView,you need to create a custom class, whichis a subclass of SurfaceView.And this custom class must,must also implement theSurfaceHolder.Callback interface.To use this new SurfaceView, you need todo two things.One, you need tosetup the SurfaceView.And two, you need to draw to theSurfaceView that you just setup.Let's talk about each of those steps, oneat a time.To set up the SurfaceView, you first usethe SurfaceViews getHolder method toacquire the SurfaceView's SurfaceHolder.Next,you register the SurfaceView forSurfaceHolder callbacks.By calling the SurfaceHolder's addCallbackmethod.Now these methods are one, surfaceCreatedwhich is called when the SurfaceView'ssurface has been created.Until this method is called you can't drawon the surface.It's not ready.Two, surfaceChanged.This method is called whenever structuralchanges,such as changing the surface's size,occurs.And three, surfaceDestroyed.And this method is called right before asurface is destroyed.Once this method returns, you can nolonger call operations that will drawon the surface.And the last setup step is to create thethreadthat will be used for executing drawingoperations on this SurfaceView.And remember, that the SurfaceHoldercallback methodswill usually be called from the mainthread not from the SurfaceView's thread.So you'll have to make sure that yousynchronize

Page 4: 6 - 2 - Graphics and Animation - Part 2 (12-26)

access to any data that is needed by boththreads.So once you've setup the SurfaceView youcan start drawing on it.To draw, you'll first acquire a lockon the canvas by calling the lockCanvasmethod.Next, you do whatever drawing operationsthat you want to do on the canvas.For example, by calling a canvas method,such as drawBitmap.And last, you unlockthe canvas, allowing Android to update thedisplay.And you'll do this bycalling the SurfaceHolder'sunlockCanvasAndPost method.So let's look at a differentimplementation ofour last example application, calledGraphicsBubbleCanvas Surface View.[BLANK_AUDIO]So here's my device.And in a moment, I'llstart upthe GraphicsCanvasBubbleSurfaceViewapplication.And when I do, the application will startup anddraw the bubble at a randomly selectedlocation on the display.But this time, instead of updating everysecond or so, this applicationwill try to do as many updates as it can.In addition,the application will also rotate thebubble view to give the appearancethat the bubble is twirling through space.So here goes.And as you can see, the bubble is smoothlyanimating both moving and rotating as itfloats along.Let's look at the source code for thisapplication.So here's theGraphicsCanvasBubbleSurfaceViewapplication open in the IDE.Now I'll open the main activity.And in onCreate, this code again loads abitmap from the resources directory.And then uses that bitmap to create aninstance of a custom view class calledBubbleView.Let's look at the BubbleView class.The BubbleView class extends SurfaceViewand implements the SurfaceHolder.Callbackinterface.The constructive for this class does a lotof housekeeping.And then down at the end of the method,

Page 5: 6 - 2 - Graphics and Animation - Part 2 (12-26)

there'sa call to the getHolder method, whichreturns a SurfaceHolder.The code takes that SurfaceHolder and thenregisters this BubbleViewfor callbacks.Let's look at what happens when thesecallbacks finally arrive.First, we see thatwhen the surface for the SurfaceView iscreated, this code createsa new thread, and then starts it.And that thread's run methodthen goes into a loop.And on each iteration of the loop,it checks to see whether the thread's beeninterrupted.And if not, it then calls the move method,which like before moves the bubble viewand returns a Boolean indicating whetheror not the BubbleView has left the screen.If these checks evaluate to true, thenthe code attempts to lock theSurfaceHolder's canvas.And ifsuccessful, the code then calls thedrawBubble method passing in the lockedcanvas.And then finally, the application unlocksthecanvas and allows Android to update thedisplay.Let's go back for one second and look atthe drawBubble method.Now, this method, first redraws thecanvas's background,then it rotates the canvas and then itredraws the bubble on the canvas.[BLANK_AUDIO].