Android. graphics package-core rendering package (drawing)

Source: Internet
Author: User
Tags drawtext


The android. graphics package is the core rendering package. It provides some basic graphics tools, such as canvas, color filter, and paint brush, allowing you to process images directly on the screen. This package provides many classes. Let's take a look at the main classes in this package. I. Canvas Android. Graphics. canvascanvas is like a canvas in a mobile phone. We can draw images or images on the canvas. Generally, when we use Android for painting, we need four components: 1. Bitmap: pixel 2. Canvas canvas: including the painting content. Write the bitmap. 3. Initial image: such as rect, bitmap, text, etc. 4. Paint: used to describe the color and type of the above initial image. Canvas class provides three constructor Methods: Public canvas (); construct a canvas object public canvas (Bitmap bitmap) with no parameters by default; construct a canvas object public canvas (GL) based on a bitmap ); to construct an object based on a GL, let's take a look at the methods provided by the canvas class: In the methods provided by the canvas class, the commonly used methods begin with draw, the method that starts with draw is easy to understand, that is, drawing a graph into the canvas, for example, drawing a bitmap into the canvas and filling the color of the graph. Example method: drawarc (rectf oval, float startangle, float sweepangle, Boolean usecenter, paint) draw an arc drawcircle (float CX, float cy, float radius, paint) the circular canvas class provides many methods. We will not repeat them here. In the following content, I will give you a few practical application examples to demonstrate how to use the canvas class. Ii. Paint android. graphics. the paintpaint class contains information that can be used to draw ry, text, bitmap types and colors. If you think of the canvas class as a canvas, you can think of the paint class as a paint brush, you can draw images and texts of different colors and styles as needed. The paint class has three constructor Methods: Public paint () to construct a default paint object public paint (INT flags); to construct a paint object based on the specified flags, after creation, you can use setflags () to change public paint (paint) constructing a paint object based on the specified paint object provides many methods to set and obtain attributes of a paint object, such as public int getcolor () get the color value of the paint object public colorfilter getcolorfilter () Get the color filter public float gettextsize () Get the font size value public void setstyle (paint. style) set the paint type. graphics. the color class defines some methods to create and convert Color value. The color is expressed as an encapsulated value. The value consists of four bytes: Alpha, red, green, and blue. These values are not left-multiplied, that is to say, any transparency is only stored in the Alpha part, not in the color components. Each part is saved in the following sequence: (alpha <24) | (Red <16) | <green <8) | blue. the value range of each part is between 0 and 255. 0 indicates that this part does not work, and 100% indicates that takes effect. Therefore, the opaque black should be 0xff000000, And the opaque white should be 0 xffffffff. The color class provides 12 constant values to represent different color values. In the development project, we can directly call these constant values to set the text, graphics, and other objects we want to modify. The color class provides a construction method without parameters. The color () color class provides some methods to create and convert color values as follows: the three methods are used to return the red, green, and blue color of a color constant value. The values are between 0 and respectively, as shown below: public static red (INT color); public static Green (INT color ); public static blue (INT color); among them, public static int RGB (INT red, int green, int blue); input red, green, and blue to return an RGB color value. For details about the following methods, refer to the android API: public static int HSV tocolor (INT Alpha, float [] HSV); public static int HSV tocolor (float [] HSV ); public static void rgbtohsv (INT red, int green, int blue, float [] HSV); public static int alpha (INT color); public static int argb (INT Alpha, int red, int green, int blue); public static colortohsv (INT color, float [] HSV); public static parsecolor (string colorstring); 4. typeface android. GRAP The hics. typefacetypeface class defines the internal types of fonts and fonts. This class is used when the paint brush is set. For example, textsize, textskewx, and textscale are used to specify how text is displayed and measured during painting. Typeface provides some constant values to represent some of its own attributes, such as bold, bold_italic, and italic. developers can use defaultfrophone sdntyle (INT style) to obtain the inherent typeface object. Readers can refer to the detailed API documentation and will not go into details here. Next, let's take a look at the main methods of typeface. The typeface class has no constructor. Generally, if a class has no constructor, it cannot be constructed to generate an object. In this case, a specific static method is usually used to obtain the object of this class. Typeface provides four static methods to indirectly obtain typeface objects: public static typeface create (typeface family, int style ); this method returns a typeface that matches an existing typeface System and the type is of the specified type. This method can be called if you want to obtain a typeface system that is similar to an existing one, but has different styles. The family parameter can be null. If it is null, the family parameter is selected from the default typeface system. Public static typefaxe create (string familyname, int style); this method returns a typeface object through the name of the given glyph system familyname and the specified type. If the name of the given font system is null, we can use the getstyle () method to obtain the true attributes of the returned typeface object. Public static typeface createfromasset (assetmanager Mgr, string path); this method returns a typeface object through the specified font data. The first parameter is the resource manager, and the second parameter is the specified font type. Public static typeface defaultfrophone sdntyle (INT style); this method returns a typeface object of the specified type. typeface also provides three other methods: Public int getstyle (); this method returns the internal type attribute public final Boolean isbold () of typeface; If getstyle () has a bold group, truepublic final Boolean isitalic (); If getstyle () if an italic bit group exists, true is returned. 5. The path class is Android. graphics. pathpath class (a group of regions) is used for plotting. It contains multiple geometric figures, such as line segments, quadratic curves, and cubic curves. Canvas is called. the drawpath () method can be used to draw a path in the defined paint mode to the drawing board or to fill out the image. It can also be used to draw the image in the method specified by the paint. 6. rectf Android. Graphics. rectf and rect Android. Graphics. rectrectf contain four single-precision floating point coordinates of a rectangle. A rectangle is represented by the coordinates of the top, bottom, and left sides of the rectangle. These coordinate value attributes can be directly accessed, and the width and height of the rectangle can be obtained using the width () and height () methods. Note: Most methods do not check whether these coordinate classifications are incorrect (that is, left <= right and top <= bottom ). rectf has four construction methods: rectf () to construct a non-parametric rectf (float left, float top, float right, float bottom) construct a rectf (rect f r) with four parameters specified. Construct a rectf object based on the specified rectf object (the left coordinate of the object remains unchanged) rectf (rect R) many methods are provided to construct a rectf object rectf Based on the given rect object. The following describes several methods: Public Boolean contain (rectf R); Determine whether a rectangle is inside this rectangle, returns true if it is within or equal to this rectangle. Similarly, public Boolean contain (float left, float top, float right, float Bot Tom) and Public Boolean contain (float X, float Y ). Public void Union (float X, float y) updates the rectangle so that it contains the vertex of the rectangle itself and (x, y. The methods provided by the rectf class are simple and easy to understand. I will not go into details about Android here. graphics. rect class, which is similar to Android. graphics. rectf is very similar. The difference is that the coordinates of the rect class are represented by an integer, while the coordinates of the rectf are represented by a single precision Floating Point. 7. Point Android. Graphics. Point is an object class of a vertex. This class has two attributes: X coordinate and Y coordinate. There are three constructors: Point (), point (int x, int y), and point (point P). The main methods are public void set (x, y ); reset the coordinate public final void offset (INT dx, int Dy) of X and Y. assign a compensation value to the coordinate. The value can be positive or negative. Public final void negate (); negative coordinate value. The Point class is similar to Android. Graphics. pointf. The difference is that the former coordinate value type is int type, while the latter coordinate value is float type. In addition, the pointf class adds several more methods, such as public final float length (); returns the distance from (0, 0) to the point. Public static float length (float X, float y); returns the distance from (0, 0) to (x, y. The following example shows the usage of the above classes: @ overrideprotected void ondraw (canvas) {paint = new paint (); paint. setcolor (color. (argb (255,255,255,255); rect = new rect (10, 20, 30, 40); canvas. drawrect (rect, paint); rectf = new rectf (40.5f, 4155f, 60.5f, 40.5f); canvas. drawrect (rectf, paint); paint. setstyle (style. stroke); canvas. drawrect (10, 50, 30, 80, paint);} In addition, we can easily draw an image through the canvas method, run The Effect and original Code are as follows: This is relatively simple. Check the Code directly. package p.com; import android. app. activity; import android. content. context; import android. content. res. resources; import android. graphics. bitmap; import android. graphics. canvas; import android. graphics. paint; import android. graphics. drawable. drawable; import android. OS. bundle; import android. view. view; public class pactivity extends activity {public void oncreate (bundle savedinstance State) {super. oncreate (savedinstancestate); myview = new myview (this); myview. loadlogo (); setcontentview (myview);} private class myview extends view {public myview (context) {super (context);} bitmap blogo; private Final paint mpaint = new paint ();/*** install in logo */Public void loadlogo () {resources r = This. getcontext (). getresources (); drawable logo = R. getdrawable (R. drawable. OMS Logo); Bitmap bitmap = bitmap. createbitmap (200,100, bitmap. config. argb_8888); canvas = new canvas (Bitmap); logo. setbounds (0, 0,200,100); logo. draw (canvas); blogo = bitmap;} protected void ondraw (canvas) {If (blogo! = NULL) {canvas. drawbitmap (blogo, 0, 0, mpaint) ;}}} draw the ry: Use the Android. graphics class

This example uses different paint object setting values to draw a variety of geometric shapes of hollow, practical, and gradient on the CAVAS canvas.

Example

"How do I draw 2D images on a computer ?" This is a problem that many android game developers often mention. In the android SDK, there is no javagraphics2d function available, but the class under Android. graphics is used to draw 2D vector diagrams. This package provides many classes and methods for Drawing Images on mobile phones, including canvas, while painting (Android. graphics. paint) class is like a color pencil. Different coincidences can be used to draw vector images of different colors and effects.

This example uses different paint object setting values to draw a variety of geometric shapes of hollow, practical, and gradient on the CAVAS canvas.

If

Sample program

The main program inherits from Android. view. in the myview class of the view, override the ondraw () method of the myview and start the painting. In ondraw (), draw the Ry on the canvas with the paint, and use the paint. setcolor () is used to change the image color and paint the image. setstyle () settings to control whether the drawn image is hollow or solid. The last section of the program is to write text directly on the canvas. With the attribute settings in the paint object, there will be different appearance modes.

Package com. graphices;
 
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. content. context;
Import Android. Graphics. Canvas;
Import Android. Graphics. color;
Import Android. Graphics. paint;
Import Android. Graphics. rectf;
Import Android. Graphics. path;
Import Android. Graphics. shader;
Import Android. Graphics. lineargradient;
Public class graphicesactivity extends activity {
/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
/* Set contentview to custom myview */
Myview = new myview (this );
Setcontentview (myview );
}
/* Customize the myview that inherits the view */
Private class myview extends View
{
Public myview (context ){
Super (context );
}
/* Override ondraw ()*/
@ Override
Protected void ondraw (canvas)
{
Super. ondraw (canvas );
/* Set the background to white */
Canvas. drawcolor (color. White );
Paint paint = new paint ();
/* De-sawtooth */
Paint. setantialias (true );
/* Set the paint color */
Paint. setcolor (color. Red );
/* Set the paint style to stroke: hollow */
Paint. setstyle (paint. style. Stroke );
/* Set the width of the paint outer frame */
Paint. setstrokewidth (3 );
/* Draw a hollow circle */
Canvas. drawcircle (40, 40, 30, paint );
/* Draw a hollow square */
Canvas. drawrect (10, 90, 70,150, paint );
/* Draw a hollow rectangle */
Canvas. drawrect (10,170, 70,200, paint );
/* Draw a hollow elliptical shape */
Rectf Re = new rectf (10,220, 70,250 );
Canvas. drawoval (Re, paint );
/* Draw a hollow triangle */
Path = New Path ();
Path. moveTo (10,330 );
Path. lineto (70,330 );
Path. lineto (40,270 );
Path. Close ();
Canvas. drawpath (path, paint );
/* Draw a hollow trapezoid */
Path path1 = New Path ();
Path1.moveto (10,410 );
Path1.lineto (70,410 );
Path1.lineto (55,350 );
Path1.lineto (25,350 );
Path1.close ();
Canvas. drawpath (path1, paint );
          
/* Set the style of paint to fill: solid */
Paint. setstyle (paint. style. Fill );
/* Set the paint color */
Paint. setcolor (color. Blue );
/* Draw a solid circle */
Canvas. drawcircle (, 40, 30, paint );
/* Draw a solid square */
Canvas. drawrect (90, 90,150,150, paint );
/* Draw a solid rectangle */
Canvas. drawrect (90,170,150,200, paint );
/* Draw a solid ellipse */
Rectf re2 = new rectf (90,220,150,250 );
Canvas. drawoval (re2, paint );
/* Draw a solid triangle */
Path path2 = New Path ();
Path2.moveto (90,330 );
Path2.lineto (150,330 );
Path2.lineto (120,270 );
Path2.close ();
Canvas. drawpath (path2, paint );
/* Draw a solid trapezoid */
Path path3 = New Path ();
Path3.moveto (90,410 );
Path3.lineto (150,410 );
Path3.lineto (135,350 );
Path3.lineto (105,350 );
Path3.close ();
Canvas. drawpath (path3, paint );
/* Set gradient */
Shader mshader = new lineargradient (0, 0, 100,100,
New int [] {color. Red, color. Green, color. Blue, color. Yellow },
Null, shader. tilemode. Repeat );
Paint. setshader (mshader );
        
/* Draw a gradient circle */
Canvas. drawcircle (, 30, paint );
/* Draw a gradient square */
Canvas. drawrect (170, 90,230,150, paint );
/* Draw a gradient rectangle */
Canvas. drawrect (170,170,230,200, paint );
/* Draw a gradient Oval */
Rectf RE3 = new rectf (170,220,230,250 );
Canvas. drawoval (RE3, paint );
/* Draw a gradient triangle */
Path path4 = New Path ();
Path4.moveto (170,330 );
Path4.lineto (230,330 );
Path4.lineto (200,270 );
Path4.close ();
Canvas. drawpath (path4, paint );
/* Draw a gradient trapezoid */
Path path5 = New Path ();
Path5.moveto (170,410 );
Path5.lineto (230,410 );
Path5.lineto (215,350 );
Path5.lineto (185,350 );
Path5.close ();
Canvas. drawpath (path5, paint );
          
/* Write */
Paint. settextsize (24 );
Canvas. drawtext (getresources (). getstring (R. String. str_text1), 240, 50, paint );
Canvas. drawtext (getresources (). getstring (R. String. str_text2), 240,120, paint );
Canvas. drawtext (getresources (). getstring (R. String. str_text3), 240,190, paint );
Canvas. drawtext (getresources (). getstring (R. String. str_text4), 240,250, paint );
Canvas. drawtext (getresources (). getstring (R. String. str_text5), 240,320, paint );
Canvas. drawtext (getresources (). getstring (R. String. str_text6), 240,390, paint );
}
}
}

 

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.