Android 2D graphics Learning (II), canvas Article 1. Basic use of canvas

Source: Internet
Author: User
Tags skia

Canvas refers to the canvas, which is an area on the screen. We can use various APIs to draw what we want. It can be said that canvas runs through the entire 2D graphics, and almost all classes in Android. graphics are directly or indirectly related to canvas. Therefore, understanding canvas is the basis for learning 2D graphics.

The official Android documentation provides a good introduction to canvas:

The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing). 

A canvas object has four basic elements:

1. A Bitmap used to save pixels

2. Draw a canvas on bitmap

3. Something to draw

4. Paint paint

1. How to obtain a canvas object.

Canvas objects can be obtained in three ways:

First, we rewrite the view. ondraw method. The canvas object in the view will be passed as a parameter. When we operate the canvas, the effect will be directly reflected in the view.

The second is when you want to create a canvas object by yourself. From the above basic elements, we can see that a canvas object must be combined with a bitmap object. Therefore, you must set a bitmap object for a canvas object.

// Obtain a bitmap object, which can also be obtained in other ways. However, you must note that bitmap must be mutable (mutable) bitmap B = bitmap. createbitmap (100,100, bitmap. config. argb_8888); canvas c = new canvas (B);/* First, a new canvas object. When you call the setbitmap method, the same effect is displayed. * canvas c = new canvas (); * C. setbitmap (B );*/

The third method is to call surfaceholder. lockcanvas () and return a canvas object.

2. What can canvas draw?

The canvas class provides a series of draw... methods, from which you can know the objects that can be drawn by canvas.

1. Fill

 public void drawARGB(int a, int r, int g, int b) public void drawColor(int color) public void drawRGB(int r, int g, int b) public void drawColor(int color, PorterDuff.Mode mode)

Because the canvas maintains a mutable bitmap, it can use these colors to fill the entire bitmap. The restricted to the current clip mentioned in the API is limited by the clip range.

 public void drawPaint(Paint paint)

Similarly, canvas can also use a paint brush to fill the entire bitmap. Similarly, the fill color is limited to the clip range. This is equivalent (but faster) to drawing
Infinitely large rectangle with the specified paint) This is equivalent to drawing a larger rectangle with the specified paint brush, but the speed is faster.

In fact, in skia, The drawpaint method is called for filling.

2. Draw geometric Images

Canvas. drawarc (slice)

Canvas. drawcircle (circle)

Canvas. drawoval (elliptical)

Canvas. drawline (line)

Canvas. drawpoint (point)

Canvas. drawrect (rectangle)

Canvas. drawroundrect (rounded rectangle)

Canvas. drawvertices (vertex)

Cnavas. drawpath (PATH)

3. Draw Images

Canvas. drawbitmap (Bitmap)

Canvas. drawpicture (image)

4. Text

Canvas. drawtext

The above lists the basic content that can be drawn by canvas. In actual use, you can use various filtering or over-pattern, or other means to achieve various effects.

3. Canvas Transformation

If it's just a simple draw... method, the canvas function is too monotonous. Canvas also provides a series of location conversion methods: rorate, scale, translate, and skew.

@ Override protected void ondraw (canvas) {canvas. translate (100,100); canvas. drawcolor (color. red); // you can see that the screen is still filled with red canvas. drawrect (New rect (-100,-100, 0, 0), new paint (); // The canvas is scaled. scale (0.5f, 0.5f); canvas. drawrect (New rect (0, 0,100,100), new paint (); canvas. translate (200, 0); canvas. rotate (30); canvas. drawrect (New rect (0, 0,100,100), new paint (); // The canvas is rotated. translate (200, 0 ); Canvas. skew (. 5f ,. 5f); // The canvas is distorted. drawrect (New rect (0, 0,100,100), new paint (); // canvas. setmatrix (matrix); // The use of matrix is later. }

Although the canvas maintains a bitmap internally, it does not represent the bitmap itself, but is more like a layer. The operations on this layer, such as translation, rotation, and scaling, do not affect the internal bitmap. They only change the coordinates, proportions, and directions of the layer relative to the internal bitmap.

4. Save and roll back canvas

To facilitate some conversion operations, canvas also provides methods to save and roll back attributes (save and restore). For example, you can save the current location of the paper ), then Rotate 90 degrees, move down 100 pixels, and draw some images. After the painting, call the restore method to return to the saved position.

Canvas provides the following APIs:

/*** Save the current matrix and clip to the private stack (implemented in skia ). Any matrix transformation and clip operations are restored when restore is called. * @ Return the return value can be passed into the restoretocount () method to return to a save status. */Public native int save ();/*** input a flag to indicate which parameters need to be restored during restore. This parameter is defined in canvas. See the following. * By default, the SAVE () method restores matrix and clip, but you can use this method to specify which restore operations are required. Only the specified matrix and clip are valid. The other parameters are used for the * savelayer () and savelayeralpha () methods. */Public native int save (INT saveflags);/*** Return to the status before the last save call. If the number of restore calls exceeds the Save method, an error occurs. */Public native void restore ();/*** return the Save status in the stack and the number of times the SAVE () API calls are interpreted as values-Restore () number of calls */Public native int getsavecount ();/*** Return to the status before calling any save () method */Public native void restoretocount (INT savecount ); /** saveflags parameter */public static final int matrix_save_flag = 0x01; // you need to restore matrix public static final int clip_save_flag = 0x02; // you need to restore clip/**. The following three parameters are used when savelayer is used. The specific function is not clear */public static final int has_alpha_layer_save_flag = 0x04; public static final int full_color_layer_save_flag = 0x08; public static final int clip_to_layer_save_flag = 0x10; public static final int all_save_flag = 0x1f; // restore all/* The specific flags about savelayer do not quite understand its meaning. How to use it in the following example */Public int savelayer (rectf bounds, paint, int saveflags) public int savelayer (float left, float top, float right, float bottom, paint, int saveflags) Public int savelayeralpha (rectf bounds, int Alpha, int saveflags) public int savelayeralpha (float left, float top, float right, float bottom, int Alpha, int saveflags)

Savelayer

In general, canvas can be regarded as a canvas. All drawing operations, such as drawbitmap and drawcircle, occur on this canvas. This canvas also defines attributes such as matrix and color. However, if you need to implement relatively complex drawing operations, such as multi-layer animation and map (a map can be formed by multiple map layers, such as the political area layer, road layer, and interest point Layer ). Canvas provides Layer Support. By default, only one layer is supported. If you need to draw by hierarchy, the android canvas can use savelayerxxx and restore to create some middle layers, which are managed according to the "stack structure:

Create a new layer to "stack". You can use savelayer and savalayeralpha to launch a layer from "stack". You can use restore and restoretocount. However, when a layer is added to the stack, subsequent drawxxx operations occur on this layer. When a layer is removed from the stack, the image drawn at this layer is "drawn" to the upper layer or canvas, when copying a layer to a canvas, you can specify the transparency of the layer. This is the public int savelayeralpha (rectf bounds,
Int Alpha, int saveflags) in this example, layers introduces the basic usage of layers: canvas can be viewed as composed of two layers. to better illustrate the problem, we will slightly modify the code. The default layer draws a red circle, and a blue circle in the new layer. The transparency of the new layer is 0 × 88.

public class Layers extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(new SampleView(this));    }    private static class SampleView extends View {        private static final int LAYER_FLAGS = Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG                | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG                | Canvas.CLIP_TO_LAYER_SAVE_FLAG;        private Paint mPaint;        public SampleView(Context context) {            super(context);            setFocusable(true);            mPaint = new Paint();            mPaint.setAntiAlias(true);        }        @Override        protected void onDraw(Canvas canvas) {            canvas.drawColor(Color.WHITE);              canvas.translate(10, 10);              mPaint.setColor(Color.RED);              canvas.drawCircle(75, 75, 75, mPaint);              canvas.saveLayerAlpha(0, 0, 200, 200, 0x88, LAYER_FLAGS);              mPaint.setColor(Color.BLUE);              canvas.drawCircle(125, 125, 75, mPaint);              canvas.restore();          }    }}

Related Article

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.