Android Graphics topic (1) --- Canvas Basics

Source: Internet
Author: User

As the opening topic of Android Graphics, we will undoubtedly discuss Canvas, the core concept of Android UI technology.

Canvas is the basis of the Android UI framework. In the Android control system, all container classes and control classes depend on Canvas in implementation. In essence, the interface is drawn by Canvas. This article will discuss the origins of Canvs and demonstrate the basic usage of Canvas through examples.

For application development, we can not go into the Implementation Details of Canvas and Android control systems, but understanding the association between Canvas and control helps us better use Canvas. If you are not familiar with the Android control system, you can refer to the blog "View and ViewGroup of the series of revealing Android principles".

Let's take a look at the code snippet of View. java, the base class of all Android controls:

…protected void onDraw(Canvas canvas) { }….

Those familiar with Andriod application development will not be unfamiliar with the onDraw method. The onDraw method in the View base class is empty, but note that the method has passed in the form parameter-Canvas object, that is, the Canvas object is already created in the UI system process, we can use it directly. Generally, we do not need to construct it ourselves. A typical use case of Canvas is to overload the onDraw method of the base class in the custom control and draw the desired image and image through the onDraw method.

Let's take a look at the code snippet of the dispatchDraw method of ViewGroup. java, which is the base class of the container class:

protected void dispatchDraw(Canvas canvas) {         …            for (int i = 0; i < count; i++) {             …                    more |= drawChild(canvas, child, drawingTime);        }           …}

The dispatchDraw method is the core function used by ViewGroup to distribute and draw sub-views. It uses the drawChild method to draw specific sub-views. Here, we only need to pay attention to the location where the Canvas object appears. Similarly, Canvas is passed as the form parameter from the dispatchDraw method and passed to the drawChild method to draw the child view.

Through code snippet analysis of two core functions: View and ViewGroup, we can clearly define the role of Canvas in the control system, and where the Canvas object used in canvas will come from.

Canvas can be understood as a Canvas in other programming languages. In the Canvas, we can draw various graphics, or draw images, at a deeper level, as described above in the dispatchDraw method of ViewGroup, we can transform the Canvas to customize the draw sub-control in the container.

This article only discusses the basic usage of Canvas, that is, using Canvas to draw basic graphics, images, and other basic usage in the onDraw method of the custom control overload.

The official Android SDK lists all the APIs of Canvas. You can click here to view details.

The following lists several APIs that are widely used in application development:

1) Draw Bitmap: drawBitmap, drawPicture

2) Draw color: drawColor, drawARGB

3) draw basic shapes: drawPoint, drawLine, drawCircle, drawArc, drawRect, drawRoundRect

4) Draw a cut area: drawPath, clipPath, clipRect, clipRegion

5) transform Canvas: save, restore, translate, scale, rotate, concat (Matrix matrix), setMatrix (Matrix matrix)

6) Draw vertex data: drawVertices, drawBitmapMesh

The six items above provide a basic overview of the most common APIs used by Canvas. For the meanings and usage of each API, see SDK. Familiar with the functions and usage of these Apis can basically meet the development needs. The following two sample codes demonstrate the basic usage of Canvas.

Example 1: Draw a Bitmap

Private static class SampleView extends View {private Bitmap mBitmap; private Bitmap mBitmap2; private Bitmap mBitmap3; private Bitmap mBitmap4; public SampleView (Context context) {super (context); setFocusable (true ); java. io. inputStream is; is = context. getResources (). openRawResource (R. drawable. beach); BitmapFactory. options opts = new BitmapFactory. options (); Bitmap bm; opts. inJustDecodeBounds = true; bm = BitmapFactory. decodeStream (is, null, opts); opts. inJustDecodeBounds = false; opts. inSampleSize = 4; bm = BitmapFactory. decodeStream (is, null, opts); mBitmap = bm; // Bitmap is = context generated by configuring Parameter Decoding. getResources (). openRawResource (R. drawable. frog); mBitmap2 = BitmapFactory. decodeStream (is); // directly decode the image int w = mBitmap2.getWidth () by opening the resource ID; int h = mBitmap2.getHeight (); int [] pixels = new int [w * h]; mBitmap2.getPixels (pixels, 0, w, 0, 0, w, h); mBitmap3 = Bitmap. createBitmap (pixels, 0, w, w, h, Bitmap. config. ARGB_8888); // uses the buffer data to construct Bitmap mBitmap4 = Bitmap. createBitmap (pixels, 0, w, w, h, Bitmap. config. ARGB_4444) ;}@ Override protected void onDraw (Canvas canvas) {canvas. drawColor (0 xFFCCCCCC); Paint p = new Paint (); p. setAntiAlias (true); // you can specify the value of the canvas that is anti-sawtooth. drawBitmap (mBitmap, 10, 10, null); canvas. drawBitmap (mBitmap2, 10,170, null); canvas. drawBitmap (mBitmap3, 110,170, null); canvas. drawBitmap (mBitmap4, 210,170, null); // draw a graph through drawBitmap }}

Example 1: a custom View SampleView for Drawing Bitmap is implemented by inheriting the Base Class View. SampleView constructs four different bitmaps in several different ways in the constructor, in the onDraw method, draw Bitmap Using the canvas passed in by the onDraw method. In this way, the control draws four images based on different coordinates on the interface. Note that the onDraw method of Android View is frequently called by the system in many scenarios, such as display, hide, and block of the interface, the cost of constructing large memory resources such as Bitmap should not be executed in the onDraw method.

Example 2: plot vertex data to achieve Deformation

Private static class SampleView extends View {private final Paint mPaint = new Paint (); private final float [] mVerts = new float [10]; private final float [] mTexs = new float [10]; private final short [] mIndices = {0, 1, 2, 3, 4, 1 }; private final Matrix mMatrix = new Matrix (); private final Matrix mInverse = new Matrix (); private static void setXY (float [] array, int index, float x, float y) {arr Ay [index * 2 + 0] = x; array [index * 2 + 1] = y;} public SampleView (Context context) {super (context); setFocusable (true ); bitmap bm = BitmapFactory. decodeResource (getResources (), R. drawable. beach); Shader s = new BitmapShader (bm, Shader. tileMode. CLAMP, Shader. tileMode. CLAMP); mPaint. setShader (s); // use BitmapShader to set the Shader float w = bm of the Paint. getWidth (); float h = bm. getHeight (); // construct our mesh s EtXY (mTexs, 0, w/2, h/2); setXY (mTexs, 1, 0, 0); setXY (mTexs, 2, w, 0 ); setXY (mTexs, 3, w, h); setXY (mTexs, 4, 0, h); // initialize the image texture ing coordinate setXY (mVerts, 0, w/2, h/2); setXY (mVerts, 1, 0, 0); setXY (mVerts, 2, w, 0); setXY (mVerts, 3, w, h ); setXY (mVerts, 4, 0, h); // initialize the vertex data array mMatrix. setScale (0.8f, 0.8f); mMatrix. preTranslate (20, 20); mMatrix. invert (mInverse); // initialize the deformation matrix} @ Override protected void onDraw (Can Vas canvas) {canvas. drawColor (0 xFFCCCCCC); // draws the background color canvas. save (); // save the canvas field canvas before deformation. concat (mMatrix); // sets the transform matrix canvas. drawVertices (Canvas. vertexMode. TRIANGLE_FAN, 10, mVerts, 0, mTexs, 0, null, 0, null, 0, 0, mPaint); // draw the image painting determined by the current vertex coordinate and texture coordinate, get the image deformation effect. Canvas. translate (0,240); // pan down the canvas. drawVertices (Canvas. vertexMode. TRIANGLE_FAN, 10, mVerts, 0, mTexs, 0, null, 0, mIndices, 0, 6, mPaint ); // draw the image painting determined by the current vertex coordinates, texture coordinates, and index array to get another image deformation effect. Canvas. restore (); // restore the canvas after the transformation is complete} @ Override public boolean onTouchEvent (MotionEvent event) {float [] pt = {event. getX (), event. getY ()}; mInverse. mapPoints (pt); // Changes Marix setXY (mVerts, 0, pt [0], pt [1]) based on the current touch position. // The vertex coordinate invalidate () is changed according to the touch position. // refresh the interface and the onDraw method is called again to return true ;}}

Example 2 is a comprehensive usage example of Canvas. It uses multiple APIs of canvas and understands this example. The usage of Canvas is quite skillful. Some new concepts in this example, such as Paint, Shader, and Matrix, will be introduced in detail later.

Example 2 has the following knowledge points:

1) The user's touch event is passed in onTouchEvent. By passing in the event parameter, you can get the coordinate points of the current touch membrane and change the algorithm parameters according to the coordinate location parameter, and then achieve the purpose of deformation according to different coordinates.

2) Calling the invaidate method of View can trigger the redrawing process of View and re-trigger the onDraw method call.

3) You can use the drawColor method of the canvas to draw the background color of the View.

4) because the Canvas parameter passed in the onDraw method is a reference, the canvas object will be used elsewhere. Therefore, if the canvas geometric parameter is changed during painting, canvas must be used before and after the conversion. save (), canvas. the restore () method is used to back up and restore the canvas site. Note that these two methods must appear in pairs, otherwise it may cause serious problems.

5) You can use concat to connect to the Maxrix matrix or translate translation, scalse scaling, and rotate rotation to transform the geometric parameters of the canvas.

6) You can use the drawVertices method to plot the image with deformation effect. The specific deformation style depends on the vertex coordinates, texture coordinates, index array, and BitmapShader set in the Paint. Flexible use of this API can achieve an Approximate 3D effect with 2D APIs. Similar to drawVertices, there is also drawBitmapMesh, which can implement complex 3D effects based on mesh vertices.

For the Running Effect of example 2, see:

This article is a basic article on Android Canvas. It mainly discusses some basic concepts and common APIs of Canvas, and will continue to cover all aspects of Canvas in subsequent articles. The next article on the Android Graphics topic will focus on the very common concept of Graphics-painting.

Welcome to our mobile phone store.:Http://vpclub.octech.com.cn/ztewd/9495.html

This article is an original article. For more information, see the source:Http://blog.csdn.net/droidpioneer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.