Android Canvas And Paint Common Drawing Function Example

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

1. Android Graphics Canvas Draw Method Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/HtR0yY0kCcI

  1. The above example demo video shows that we can choose the canvas draw method from the drop-down spinner view list.
  2. 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.

  1. Below are the example android project files.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\CANVASPAINT
    │   .gitignore
    │   build.gradle
    │   gradle.properties
    │   gradlew
    │   gradlew.bat
    │   settings.gradle
    │
    ├───.idea
    │       gradle.xml
    │       misc.xml
    │       modules.xml
    │       runConfigurations.xml
    │
    ├───app
    │   │   .gitignore
    │   │   build.gradle
    │   │   proguard-rules.pro
    │   │
    │   └───src
    │       ├───androidTest
    │       │   └───java
    │       │       └───com
    │       │           └───dev2qa
    │       │               └───canvaspaint
    │       │                       ExampleInstrumentedTest.java
    │       │
    │       ├───main
    │       │   │   AndroidManifest.xml
    │       │   │
    │       │   ├───java
    │       │   │   └───com
    │       │   │       └───dev2qa
    │       │   │           └───canvaspaint
    │       │   │                   CanvasExampleView.java
    │       │   │                   ConstantsUtil.java
    │       │   │                   MainActivity.java
    │       │   │                   test.java
    │       │   │
    │       │   └───res
    │       │       ├───drawable
    │       │       │       ic_launcher_background.xml
    │       │       │
    │       │       ├───drawable-v24
    │       │       │       ic_launcher_foreground.xml
    │       │       │
    │       │       ├───layout
    │       │       │       activity_main.xml
    │       │       │       layout.xml
    │       │       │
    │       │       ├───mipmap-anydpi-v26
    │       │       │       ic_launcher.xml
    │       │       │       ic_launcher_round.xml
    │       │       │
    │       │       ├───mipmap-hdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-mdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       └───values
    │       │               arrays.xml
    │       │               colors.xml
    │       │               strings.xml
    │       │               styles.xml
    │       │
    │       └───test
    │           └───java
    │               └───com
    │                   └───dev2qa
    │                       └───canvaspaint
    │                               ExampleUnitTest.java
    │
    └───gradle
        └───wrapper
                gradle-wrapper.jar
                gradle-wrapper.properties
  2. There are six core files in this example.
  3. MainActivity.java
  4. CanvasExampleView.java
  5. ConstantsUtil.java
  6. activity_main.xml
  7. arrays.xml
  8. strings.xml

2.1 Main Activity Java Class.

  1. 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.

  1. 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;
    
    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.

  1. ConstantsUtil.java
    package com.dev2qa.canvaspaint;
    
    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.

  1. 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.

  1. 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.

  1. 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>
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x