How to use Path to draw Cubic and Quadratic Bezier curves in android Canvas

In this android programming source code example, we are going to use Path to draw Cubic and Quadratic Bezier curves in android Canvas.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to use Path to draw Cubic and Quadratic Bezier curves in android Canvas.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <view class="com.bluapp.androidview2.Canvas.CanvasActivity21$canvas21"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;


public class CanvasActivity21 extends AppCompatActivity {

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

    public static class canvas21 extends View {
        private Paint paint;
        private Path path;
        public canvas21(Context context, AttributeSet attributeSet){
            super(context, attributeSet);
            path = new Path();
            paint = new Paint();
            paint.setStyle(Paint.Style.STROKE);
        }

        @Override
        protected void onDraw(Canvas canvas){
            super.onDraw(canvas);
            paint.setColor(getResources().getColor(R.color.colorAccent));
            paint.setStrokeWidth(3);
            path.moveTo(50,50);
            path.cubicTo(300, 50, 100, 400, 400, 400);
            canvas.drawPath(path, paint);

            path.reset();
            paint.setColor(getResources().getColor(R.color.colorPrimary));
            paint.setStrokeWidth(1);
            path.moveTo(50,50);
            path.lineTo(300,50);
            path.lineTo(100,400);
            path.lineTo(400,400);
            canvas.drawPath(path, paint);

        }

    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment