Custom Controls (1): Paint and Canvas, paintcanvas
Preface:
Two classes required for custom controls: Paint and Canvas
Paint --- equivalent to drawing "pen"
Canvas --- equivalent to drawing "paper"
1. Paint
A drawing pen is used to set colors, line width, line transparency, and other familiarity.
Let's take a look at all the setXX () Methods of the Paint class.
Commonly used:
- Paint. setAntiAlias (true); // anti-aliasing Function
- Paint. setColor (Color. RED); // you can specify the paint Color.
- Paint. setStyle (Style. FILL); // you can specify a filling Style.
- Paint. setStrokeWidth (10); // you can specify the paint width in pixels.
- Paint. setShadowLayer (10, 15, 15, Color. GREEN); // sets the shadow.
Here we will briefly introduce the attributes of 3rd and 5th methods.
1. paint. setStyle (Style. XXX); // you can specify a filling Style.
Style. FILL, that is, paint brush filling. For example, if you want to draw a rectangle, the inside of the rectangle is filled.
Style. STROKE, that is, only the border drawn by the paint brush,
Style. FILL_AND_STROKE, that is, the border line and internal fill have
2. paint. setShadowLayer (10, 15, 15, Color. GREEN); // sets the shadow.
(1) radius (angle), that is, the tilt angle of the shadow,
(2) dx, that is, the offset of the Shadow x direction.
(3) dy, that is, the offset of the Shadow y direction.
(4) shadowColor, that is, the shadow color
Ii. Canvas
Canvas and paper.
The main method of the Canvas class is drawXXX (), that is, draw a line, draw a circle, draw a rectangle, draw a text, draw an ellipse, and so on.
Iii. Practice
Let's write a few examples to use Paint to control attributes such as the width and color of the Paint brush line.
Use Canvas to control the drawn shape
First, define a class to inherit from the View class and override the three constructor methods.
Override the onDraw () method, which is used to draw custom controls
@ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas); // you can specify paint = new Paint (); paint. setStyle (Paint. style. FILL); paint. setColor (Color. RED); paint. setStrokeWidth (2); // unit: px paint. setTextSize (30); // set the text size // set the Canvas attributes. Note that the onDraw () method parameter has a canvas object. Do not create a Canvas in the new one. drawRGB (255,255,255); canvas. drawLine (200,200,600,200, paint); // draw a horizontal line canvas from coordinate (200,200) to coordinate (600,200) with a red color. drawRect (200,420,600,520, paint); // draw a red solid rectangular canvas with a coordinate (200,420) in the upper left corner and a width of 400 and a height of 100. drawCircle (400,800,100, paint); // draw a red solid circular canvas with a circle coordinate (400,800) and a radius of 100. drawText ("this is the drawn text", paint); // draw a text with the start coordinate on the left}
Use in activity
: