Question:I am experimenting with native drawing using the Java Canvas API on Android. As far as I can understand, Canvas is built as an abstraction on top of
Skiagraphics engine. I’m willing to pass the Canvas object obtained in the OnDraw() method of a view to native code and draw using C++ and the Skia API.
What would be the best way to gain access to the
SkCanvaspointer after passing the java
Canvasobject to native code using
Here is the information I have been able to assimilate, which ultimately boils down to accessing a private member from the instance a native platform object.
Source code of
Canvas.javafrom https://cs.android.com/android/platform/superproject/+/master:frameworks/base/graphics/java/android/graphics/Canvas.java;l=59 shows that it has private variable named
frameworks/base/graphics/java/android/graphics/BaseCanvas.java) which can be accessed via reflection through the function declared below.
mNativeCanvasWrapper, among other things, is passed to all functions responsible for drawing. Following the trail of one such function (
getWidth()), I can see it’s JNI registration in https://cs.android.com/android/platform/superproject/+/master:frameworks/base/libs/hwui/jni/android_graphics_Canvas.cpp;l=692
Canvas*pointer actually points to a class called
SkiaCanvas, which inherits from the Canvas base class. Definition for the class can be found at
frameworks/base/libs/hwui/SkiaCanvas.cpp. This is the class that contains the actual pointer to the
SKCanvasobject that I need (marked private), as can be seen at https://cs.android.com/android/platform/superproject/+/master:frameworks/base/libs/hwui/SkiaCanvas.h;l=219.
How can I obtain the
SKCanvaspointer from a
SkiaCanvaspointer, given that it’s marked private and the only getter is marked protected?
Answer:The answer is in two parts.
First, getting the
Canvas*out of the JNI object:
If you have better answer, please add a comment about this, thank you!