3

The Android View Class has a method called onDraw, and onDraw gets passed a canvas. Only the user never explicitly creates the canvas that gets passed and appears to have no other means by which to access it.

What is the canvas that gets passed to onDraw, where is it created and is there a way to access it?

Thank you for your help.

Kuffs
  • 35,581
  • 10
  • 79
  • 92
Antion19
  • 227
  • 2
  • 7
  • just set a breakpoint in View.onDraw and scan the frames below, one of them should be ViewRoot – pskink Oct 13 '13 at 18:24
  • The `Canvas` object is just a wrapper around the native 2D library functions with a lock on a drawing surface. If you want access to that drawing surface, you can't without accessing the private API, and it would be unwise to do so anyway. What exactly are you trying to do outside of `onDraw`? If we knew your intent, we might be better able to suggest how to accomplish it. – Dave Oct 14 '13 at 06:43

2 Answers2

0

As concluded from Understanding Canvas and Surface concepts

A view implicitly has a canvas associated with it. When invalidate() is called from within a specific view, or for a specific view (i.e. View v and you then call v.invalidate()) the canvas associated with that view is sent to the View's onDraw method.

When a view contains other views, the hierarchical view tree is traversed and redrawn starting from the view that made the invalidate call.

Community
  • 1
  • 1
0

ViewRootImpl, the topmost class in the view hierarchy, requests a Canvas for the entire visible window, and passes it to the top level ViewGroup of your Activity. Each ViewGroup then passes a concatenatedsubsetted version of this Canvas to each child View's draw() method.

As far as I know, it's not possible to manipulate the Canvas outside of onDraw() (and related methods).

You might try calling draw() yourself with a new instance of Canvas that you control. That won't draw anything onto the screen, but you'll be able to read the Canvas elsewhere in your class, convert it to a bitmap, etc. See this answer for an example: Convert view to bitmap on Android

Community
  • 1
  • 1
cnnr
  • 1,626
  • 14
  • 17