Getting started with custom view -- simple drawing of fan and pie

If you want to draw a fan on your interface, the normal controls you use do not have this function. At this time, we can use the custom view to draw the fan

Next, let's learn how to use custom view to draw:

1: Create a class

1: Let's create a class, inherit from View, and then override two construction methods

    //We tune it up.
    public _view(Context context) {
    //System tuning
    public _view(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

Why create two?

The first is for us to call, and the second is for android system call.

2: Override method:

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

    protected void onDraw(Canvas canvas) {

Then the onDraw method starts to draw.

2: Start drawing

Create a brush first, then add color to the brush

        //Add brushes
        Paint paint = new Paint();


Because the sector is part of the circle, the size of the circle needs to determine the starting position of a rectangle. The following picture:

Now that we understand this concept, we can start to draw the fan

        //Fillet rectangle
        RectF rectF = new RectF(100,100,getWidth()-100,getWidth()-100);
        //          How many degrees to start with and how many degrees to draw

In order to make our fan-shaped drawing more beautiful, we can add


Otherwise, the edge of the fan-shaped drawing is potholed.


The effect is as follows:

Then we continue to draw:


As shown in the picture:

We just need to pay attention to:

canvas.drawArc(rectF,0,90,true,paint);//The second parameter indicates how many degrees to draw, and the third parameter indicates how many degrees to draw

Then we can draw a complete pie chart!

Three: Quote

We have defined this class. If it is not referenced, it has no effect. So where is the reference?

In fact, it's very simple. We just need to refer to the following in the activity layout file:

<LinearLayout xmlns:android=""
        android:layout_height="match_parent" />






Tags: Android

Posted on Sun, 05 Jan 2020 10:35:00 -0800 by darkcarnival