Android custom View and draw a clock

Source: Internet
Author: User

Android custom View and draw a clock
Overview:

When the View provided by Android cannot meet the needs of developers, the custom View plays a very good role.
To create a custom View, you must inherit from the View class and implement at least one constructor and two methods: onMeasure () and onDraw ();
OnMeasure () is used to set the size of the custom View, and onDraw () is used to draw the content in the View.

In the onDraw () method, you must call the paint brush to draw a drawing or text. The Canvas object is used to draw a template,The methods used to draw graphic text in the Canvas class are as follows:

DrawRect (RectF rect, Paint paint) // draws a region. The parameter is set to RectF.

DrawPath (Path path, Paint paint) // draw a Path. Parameter 1 is the Path object.

DrawBitmap (Bitmap bitmap, Rect src, Rect dst, Paint paint) // map. The first parameter is our regular Bitmap object, and the second parameter is the source region (here it is bitmap ), parameter 3 is the target area (the position and size of the canvas should be used), and parameter 4 is the Paint brush object, because the possibility of scaling and stretching is used, when the original Rect is not equal to the target Rect, the performance will be greatly reduced.

DrawLine (float startX, float startY, float stopX, float stopY, Paintpaint) // draw a line. the X axis position of the starting point and the Y axis position of the starting point, the X axis horizontal position at the end of the three parameters, the four Y axis vertical position, and the last parameter is the Paint brush object.

DrawPoint (float x, float y, Paint paint) // specifies a painting point. The parameter is a horizontal x axis, the parameter is a vertical y axis, and the third parameter is a Paint object.

DrawText (String text, float x, floaty, Paint paint) // render the text. In addition to the above, the Canvas class can also depict the text. The first parameter is a String text, and the second x axis is used, the three y axes and four parameters are the Paint objects.

DrawOval (RectF oval, Paint paint) // draws an elliptical image. The first parameter is the scan area, and the second parameter is the paint object;

DrawCircle (float cx, float cy, float radius, Paint paint) // draw a circle. The first parameter is the X axis of the center, the second parameter is the Y axis of the center, and the third parameter is the radius, parameter 4 is the paint object;

DrawArc (RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint) // draw an arc. The first parameter is a RectF object, the boundary of an elliptical area in a rectangle is defined in shape, size, and arc. Parameter 2 is the starting angle (degree) at the beginning of the arc, and parameter 3 is the scanning angle (degree) which starts to be measured clockwise, parameter 4 is if this is true, including the arc at the center of the elliptic, and closes it. If it is false, it will be an arc, and parameter 5 is the Paint object.

Paint objects must be painted with a Paint brush. The methods in the Paint class include:

SetARGB (int a, int r, int g, int B) // set the color of the Paint object. Parameter 1 is the alpha transparent value.

SetAlpha (int a) // set the alpha opacity in the range of 0 ~ 255

SetAntiAlias (boolean aa) // indicates whether the image is anti-sawtooth.

SetColor (int color) // set the Color. Here, the color class defined in Android contains some common Color definitions.

SetTextScaleX (float scaleX) // sets the text zoom factor. 1.0f is the original

SetTextSize (float textSize) // set the font size

SetUnderlineText (booleanunderlineText) // set the underline

Demo

Write a custom clock View:

Public class MyView extends View {private int width; private int height; private Paint mPaintLine; private Paint mPaintCircle; private Paint mPaintHour; private Paint mPaintMinute; private Paint mPaintSec; private Paint mPaintText; private Calendar mCalendar; public static final int NEED_INVALIDATE = 0X23; // call the redraw method private handler Handler = new handler () in Handler every second () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case NEED_INVALIDATE: mCalendar = Calendar. getInstance (); invalidate (); // tells the UI main thread to re-draw handler. sendEmptyMessageDelayed (NEED_INVALIDATE, 1000); break; default: break ;}}; public MyView (Context context) {super (context);} public MyView (Context context, AttributeSet attrs) {super (context, attrs); mCalendar = Calendar. getInstance (); mPaintLine = new Paint (); mPaintLine. setColor (Color. BLUE); mPaintLine. setStrokeWidth (10); mPaintCircle = new Paint (); mPaintCircle. setColor (Color. GREEN); // set the color mPaintCircle. setStrokeWidth (10); // set the width of mPaintCircle. setAntiAlias (true); // you can specify whether the image is anti-sawtooth. setStyle (Paint. style. STROKE); // set the painting style mPaintText = new Paint (); mPaintText. setColor (Color. BLUE); mPaintText. setStrokeWidth (10); mPaintText. setTextAlign (Paint. align. CENTER); mPaintText. setTextSize (40); mPaintHour = new Paint (); mPaintHour. setStrokeWidth (20); mPaintHour. setColor (Color. BLUE); mPaintMinute = new Paint (); mPaintMinute. setStrokeWidth (15); mPaintMinute. setColor (Color. BLUE); mPaintSec = new Paint (); mPaintSec. setStrokeWidth (10); mPaintSec. setColor (Color. BLUE); handler. sendEmptyMessage (NEED_INVALIDATE); // send a message to handler to enable repainting.} @ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); width = getDefaultSize (rows (), widthMeasureSpec); height = getDefaultSize (rows (), heightMeasureSpec); setMeasuredDimension (width, height );} @ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas); int circleRadius = 400; // draw a large circle canvas. drawCircle (width/2, height/2, circleRadius, mPaintCircle); // draw a circle center canvas. drawCircle (width/2, height/2, 20, mPaintCircle); // rotate the canvas in sequence and draw each scale and corresponding number for (int I = 1; I <= 12; I ++) {canvas. save (); // save the current canvas. rotate (360/12 * I, width/2, height/2); // start from left: Start position x coordinate, start position y coordinate, end position x coordinate, end position y coordinate, paint Brush (a Paint object) canvas. drawLine (width/2, height/2-circleRadius, width/2, height/2-circleRadius + 30, mPaintCircle); // left: text content, starting position x coordinate, start position y coordinate, brush canvas. drawText (+ I, width/2, height/2-circleRadius + 70, mPaintText); canvas. restore (); //} int minute = mCalendar. get (Calendar. MINUTE); // get the current number of minutes int hour = mCalendar. get (Calendar. HOUR); // get the current HOUR int sec = mCalendar. get (Calendar. SECOND); // get the current number of seconds float minuteDegree = minute/60f * 360; // get the angle canvas of the sub-needle rotation. save (); canvas. rotate (minuteDegree, width/2, height/2); canvas. drawLine (width/2, height/2-250, width/2, height/2 + 40, mPaintMinute); canvas. restore (); float hourDegree = (hour * 60 + minute)/12f/60*360; // get the clock Rotation Angle canvas. save (); canvas. rotate (hourDegree, width/2, height/2); canvas. drawLine (width/2, height/2-200, width/2, height/2 + 30, mPaintHour); canvas. restore (); float secDegree = sec/60f * 360; // get the second-hand rotation angle canvas. save (); canvas. rotate (secDegree, width/2, height/2); canvas. drawLine (width/2, height/2-300, width/2, height/2 + 40, mPaintSec); canvas. restore ();}}

The custom View needs to be loaded in the layout. The name must be the full name (including the package name ):
Activity_timer


  
      
   
  

The main activity is setContentView.

public class TimerActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_timer);    }}

Demo result:

 

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.