Android Canvas And Paint Common Drawing Function Example

This example will show you how to use various android.graphics.Canvas methods to draw text, point, line, circle, rectangle, oval, arc and self defined shapes.

1. Android Graphics Canvas Draw Method Example.

You can choose the canvas draw method from the drop down spinner view list. After select one the app will use that method to draw a shape or text in the below custom view.

2. Android Canvas Draw Method Example Source Code.

android canvas and paint common function source files

There are six core files in this example.

  1. MainActivity.java
  2. CanvasExampleView.java
  3. ConstantsUtil.java
  4. activity_main.xml
  5. arrays.xml
  6. strings.xml

2.1 Main Activity Java Class.

MainActivity.java

package com.dev2qa.canvaspaint;

import android.content.Context;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("dev2qa.com - Android Canvas Paint Drawing Example.");

        final Context context = getApplicationContext();

        final LinearLayout drawingExampleLayout = (LinearLayout)findViewById(R.id.exampleLinearLayout);

        // Must declare the custom view here, otherwise the custom view's onDraw method will not be invoked after call invalidate method.
        final CanvasExampleView canvasExampleView = new CanvasExampleView(context);

        final Resources resources = getResources();

        /* Get canvas spinner and set it's on item selected listener. */
        Spinner canvasSpinner = (Spinner)findViewById(R.id.canvasSpinner);
        canvasSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                // Remove all views first.
                drawingExampleLayout.removeAllViews();

                // Add custom canvasExampleView.
                drawingExampleLayout.addView(canvasExampleView);

                Object selectedItemObj = adapterView.getAdapter().getItem(i);

                String itemText = (String)selectedItemObj;

                if(itemText.equals(resources.getString(R.string.draw_text)))
                {
                    canvasExampleView.drawText();
                }else if(itemText.equals(resources.getString(R.string.draw_point)))
                {
                    canvasExampleView.drawPoint();
                }else if(itemText.equals(resources.getString(R.string.draw_two_point)))
                {
                    canvasExampleView.drawTwoPoint();
                }else if(itemText.equals(resources.getString(R.string.draw_line)))
                {
                    canvasExampleView.drawLine();
                }else if(itemText.equals(resources.getString(R.string.draw_two_line)))
                {
                    canvasExampleView.drawTwoLine();
                }else if(itemText.equals(resources.getString(R.string.draw_rectangle)))
                {
                    canvasExampleView.drawRectangle();
                }else if(itemText.equals(resources.getString(R.string.draw_round_rectangle)))
                {
                    canvasExampleView.drawRoundRectangle();
                }else if(itemText.equals(resources.getString(R.string.draw_arc)))
                {
                    canvasExampleView.drawArc();
                }else if(itemText.equals(resources.getString(R.string.draw_oval)))
                {
                    canvasExampleView.drawOval();
                }else if(itemText.equals(resources.getString(R.string.draw_path)))
                {
                    canvasExampleView.drawPath();
                }else if(itemText.equals(resources.getString(R.string.draw_circle_path_text)))
                {
                    canvasExampleView.drawCirclePathText();
                }else if(itemText.equals(resources.getString(R.string.draw_circle)))
                {
                    canvasExampleView.drawCircle();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }
}

2.2 Custom View Java Class.

CanvasExampleView.java

package com.dev2qa.canvaspaint;

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.view.View;

/**
 * Created by zhaosong on 2018/6/18.
 */

public class CanvasExampleView extends View {

    private String action = "";

    public CanvasExampleView(Context context) {
        super(context);

        setFocusable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();

        paint.setTextSize(100);

        paint.setColor(Color.GREEN);

        // Set the point, line width. If do not set this, the point is too small to see, the line is too thin also.
        paint.setStrokeWidth(30);

        // Fill out the background color to refresh the screen.
        canvas.drawColor(Color.BLUE);

        if(ConstantsUtil.DRAW_POINT.equals(action))
        {
            // Draw one point in pixel.
            canvas.drawPoint(100, 200, paint);
        }else if(ConstantsUtil.DRAW_TWO_POINT.equals(action))
        {
            // Draw multiple points ( two point ) in pixel.
            float pointsArray[] = {180, 260, 260, 300};
            canvas.drawPoints(pointsArray, paint);
        }else if(ConstantsUtil.DRAW_ARC.equals(action))
        {
            RectF rectF = new RectF(100, 200, 800, 900);
            paint.setAlpha(0x88);
            canvas.drawArc(rectF, 30, 100, true, paint);

        }else if(ConstantsUtil.DRAW_CIRCLE.equals(action))
        {
            // Draw a circle.
            canvas.drawCircle(600,800, 600, paint);
        }else if(ConstantsUtil.DRAW_CIRCLE_PATH_TEXT.equals(action))
        {
            Path arcPath = new Path();

            arcPath.addCircle(500, 800, 600, Path.Direction.CW);

            canvas.drawTextOnPath("dev2qa.com", arcPath, 600, 0, paint);

        }else if(ConstantsUtil.DRAW_LINE.equals(action))
        {
            // Draw the long line.
            canvas.drawLine(100, 500, 1000, 510, paint);
        }else if(ConstantsUtil.DRAW_OVAL.equals(action))
        {
            paint.setARGB(0x77, 0x11, 0x00, 0x66);
            RectF rectF = new RectF(100, 200, 800, 800);
            canvas.drawOval(rectF, paint);
        }else if(ConstantsUtil.DRAW_PATH.equals(action))
        {
            Path path = new Path();

            // Set start point.
            path.moveTo(100, 200);

            // Path one.
            path.lineTo(500, 800);

            // Path two.
            path.lineTo(300, 1000);

            // Path complete.
            path.close();

            canvas.drawPath(path, paint);

        }else if(ConstantsUtil.DRAW_RECTANGLE.equals(action))
        {
            paint.setStyle(Paint.Style.STROKE);
            // Draw rectangle
            canvas.drawRect(100, 1000, 800, 1300, paint);
        }else if(ConstantsUtil.DRAW_ROUND_RECTANGLE.equals(action))
        {
            RectF rectF = new RectF(100, 200, 800, 1000);
            canvas.drawRoundRect(rectF, 100, 200, paint);
        }else if(ConstantsUtil.DRAW_TEXT.equals(action))
        {
            paint.setTextAlign(Paint.Align.CENTER);
            // Draw text.
            canvas.drawText("dev2qa.com", 600, 600, paint);
        }else if(ConstantsUtil.DRAW_TWO_LINE.equals(action))
        {
            // Draw two short lines.
            float linePointsArray[] = {10, 550, 120, 600, 280, 650, 800,610};
            canvas.drawLines(linePointsArray, paint);
        }
    }

    public void drawPoint()
    {
        action = ConstantsUtil.DRAW_POINT;
        invalidate();
    }

    public void drawTwoPoint()
    {
        action = ConstantsUtil.DRAW_TWO_POINT;
        invalidate();
    }

    public void drawLine()
    {
        action = ConstantsUtil.DRAW_LINE;
        invalidate();
    }

    public void drawTwoLine()
    {
        action = ConstantsUtil.DRAW_TWO_LINE;
        invalidate();
    }

    public void drawCircle()
    {
        action = ConstantsUtil.DRAW_CIRCLE;
        invalidate();
    }

    public void drawCirclePathText()
    {
        action = ConstantsUtil.DRAW_CIRCLE_PATH_TEXT;
        invalidate();
    }

    public void drawRectangle()
    {
        action = ConstantsUtil.DRAW_RECTANGLE;
        invalidate();
    }

    public void drawRoundRectangle()
    {
        action = ConstantsUtil.DRAW_ROUND_RECTANGLE;
        invalidate();
    }

    public void drawOval()
    {
        action = ConstantsUtil.DRAW_OVAL;
        invalidate();
    }

    public void drawArc()
    {
        action = ConstantsUtil.DRAW_ARC;
        invalidate();
    }

    public void drawPath()
    {
        action = ConstantsUtil.DRAW_PATH;
        invalidate();
    }

    public void drawText()
    {
        action = ConstantsUtil.DRAW_TEXT;
        invalidate();
    }
}

2.3 Constant Util Java Class.

ConstantsUtil.java

package com.dev2qa.canvaspaint;

/**
 * Created by zhaosong on 2018/6/19.
 */

public class ConstantsUtil {

    public static String DRAW_TEXT = "DRAW_TEXT";

    public static String DRAW_POINT = "DRAW_POINT";

    public static String DRAW_TWO_POINT = "DRAW_TWO_POINT";

    public static String DRAW_LINE = "DRAW_LINE";

    public static String DRAW_TWO_LINE = "DRAW_TWO_LINE";

    public static String DRAW_CIRCLE = "DRAW_CIRCLE";

    public static String DRAW_RECTANGLE = "DRAW_RECTANGLE";

    public static String DRAW_ROUND_RECTANGLE = "DRAW_ROUND_RECTANGLE";

    public static String DRAW_ARC = "DRAW_ARC";

    public static String DRAW_OVAL = "DRAW_OVAL";

    public static String DRAW_PATH = "DRAW_PATH";

    public static String DRAW_CIRCLE_PATH_TEXT = "DRAW_CIRCLE_PATH_TEXT";
}

2.4 Main Activity Layout Xml File.

app / res / layout / activity_main.xml

<TableLayout
    android:padding="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:gravity="end"
            android:text="Canvas Function : " />

        <Spinner
            android:id="@+id/canvasSpinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:entries="@array/canvas_function"
            android:spinnerMode="dropdown"/>

    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/exampleLinearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_span="2" />

    </TableRow>

</TableLayout>

2.5 Resource Arrays Definition Xml File.

app / res / values / arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Canvas function spinner items. -->
    <string-array name="canvas_function">
        <item>@string/select_function</item>
        <item>@string/draw_text</item>
        <item>@string/draw_point</item>
        <item>@string/draw_two_point</item>
        <item>@string/draw_line</item>
        <item>@string/draw_two_line</item>
        <item>@string/draw_circle</item>
        <item>@string/draw_rectangle</item>
        <item>@string/draw_round_rectangle</item>
        <item>@string/draw_arc</item>
        <item>@string/draw_oval</item>
        <item>@string/draw_path</item>
        <item>@string/draw_circle_path_text</item>
    </string-array>

</resources>

2.6 Resource Strings Definition Xml File.

app / res / values / strings.xml

<resources>

    <string name="app_name">CanvasPaint</string>

    <string name="select_function">Select Function</string>

    <!-- Canvas drawing function example string.-->

    <string name="draw_text">Draw Text</string>

    <string name="draw_point">Draw Point</string>

    <string name="draw_two_point">Draw Two Point</string>

    <string name="draw_line">Draw Line</string>

    <string name="draw_two_line">Draw Two Line</string>

    <string name="draw_circle">Draw Circle</string>

    <string name="draw_rectangle">Draw Rectangle</string>

    <string name="draw_round_rectangle">Draw Round Rectangle</string>

    <string name="draw_arc">Draw Arc</string>

    <string name="draw_oval">Draw Oval</string>

    <string name="draw_path">Draw Path</string>

    <string name="draw_circle_path_text">Draw Circle Path Text</string>

</resources>
(Visited 714 times, 6 visits today)
READ :   Android Change Screen Brightness Programmatically Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.