[java] How to draw circle by canvas in Android?

I want to draw circle by canvas. Here is my code:

[MyActivity.java]:

public class MyActivity extends Activity 
{
 public void onCreate(Bundle savedInstanceState) 
   {
      ...
      setContentView(new View(this,w,h));
   }
        
}

[View.java]:

public class View extends SurfaceView
{
    public View(Context context, int w, int h)
    {
        super(context);
        Canvas grid = new Canvas(Bitmap.createBitmap(h,w, Bitmap.Config.ARGB_8888));
        grid. drawColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        grid.drawCircle(w/2, h/2 , w/2, paint);
    }
}

So I have just black screen without circle. Why it does not work? How to fix it?

This question is related to java android android-canvas

The answer is


public class CircleView extends View {

    private static final String COLOR_HEX = "#E74300";
    private final Paint drawPaint;
    private       float size;

    public CircleView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        drawPaint = new Paint();
        drawPaint.setColor(Color.parseColor(COLOR_HEX));
        drawPaint.setAntiAlias(true);
        setOnMeasureCallback();
    }

    @Override
    protected void onDraw(final Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(size, size, size, drawPaint);
    }

    private void setOnMeasureCallback() {
        ViewTreeObserver vto = getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                removeOnGlobalLayoutListener(this);
                size = getMeasuredWidth() / 2;
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void removeOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener listener) {
        if (Build.VERSION.SDK_INT < 16) {
            getViewTreeObserver().removeGlobalOnLayoutListener(listener);
        } else {
            getViewTreeObserver().removeOnGlobalLayoutListener(listener);
        }
    }
}

Xml example: will produce a circle of 5dp

 <com.example.CircleView
        android:layout_width="10dp"
        android:layout_height="10dp"/>

Try this

enter image description here

The entire code for drawing a circle or download project source code and test it on your android studio. Draw circle on canvas programmatically.

import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.graphics.Point;
    import android.graphics.PorterDuff;
    import android.graphics.PorterDuffXfermode;
    import android.graphics.Rect;
    import android.graphics.RectF;
    import android.widget.ImageView;


        public class Shape {

            private Bitmap bmp;
            private ImageView img;
            public Shape(Bitmap bmp, ImageView img) {

                this.bmp=bmp;
                this.img=img;
                onDraw();
            }

            private void onDraw(){
                 Canvas canvas=new Canvas();
                 if (bmp.getWidth() == 0 || bmp.getHeight() == 0) {
                     return;
                }

                int w = bmp.getWidth(), h = bmp.getHeight();

                Bitmap roundBitmap = getRoundedCroppedBitmap(bmp, w);

                img.setImageBitmap(roundBitmap);

            }

            public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
                Bitmap finalBitmap;
                if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
                    finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                            false);
                else
                    finalBitmap = bitmap;
                Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                        finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(output);

                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                        finalBitmap.getHeight());

                paint.setAntiAlias(true);
                paint.setFilterBitmap(true);
                paint.setDither(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(Color.parseColor("#BAB399"));
                canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f, finalBitmap.getHeight() / 2 + 0.7f, finalBitmap.getWidth() / 2 + 0.1f, paint);
                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                canvas.drawBitmap(finalBitmap, rect, rect, paint);

                return output;
            }

Here is example to draw stroke circle canvas

val paint = Paint().apply {
    color = Color.RED
    style = Paint.Style.STROKE
    strokeWidth = 10f
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Example to draw solid circle canvas

val paint = Paint().apply {
    color = Color.RED
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Hope it help


If you are using your own CustomView extending View class, you need to call canvas.invalidate() method which will internally call onDraw method. You can use default API for canvas to draw a circle. The x, y cordinate define the center of the circle. You can also define color and styling in paint & pass the paint object.

public class CustomView extends View {

    public CustomView(Context context,  AttributeSet attrs) {
        super(context, attrs);
        setupPaint();
    }
}

Define default paint settings and canvas (Initialise paint in constructor so that you can reuse the same object everywhere and change only specific settings wherever required)

private Paint drawPaint;

// Setup paint with color and stroke styles
private void setupPaint() {
    drawPaint = new Paint();
    drawPaint.setColor(Color.BLUE);
    drawPaint.setAntiAlias(true);
    drawPaint.setStrokeWidth(5);
    drawPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    drawPaint.setStrokeJoin(Paint.Join.ROUND);
    drawPaint.setStrokeCap(Paint.Cap.ROUND);
}

And initialise canvas object

private Canvas canvas;

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.canvas = canvas;
    canvas.drawCircle(xCordinate, yCordinate, RADIUS, drawPaint);
}

And finally, for every view refresh or new draw on the screen, you need to call invalidate method. Remember your entire view is redrawn, hence this is an expensive call. Make sure you do only the necessary operations in onDraw

canvas.invalidate();

For more details on canvas drawing refer https://medium.com/@mayuri.k18/android-canvas-for-drawing-and-custom-views-e1a3e90d468b


    private Paint green = new Paint();

    private int greenx , greeny;


 green.setColor(Color.GREEN);

        green.setAntiAlias(false);

        canvas.drawCircle(greenx,greeny,20,green);

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity 
{

     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(new MyView(this));
     }

     public class MyView extends View
     {
         Paint paint = null;
         public MyView(Context context) 
         {
              super(context);
              paint = new Paint();
         }

         @Override
         protected void onDraw(Canvas canvas) 
         {
            super.onDraw(canvas);
            int x = getWidth();
            int y = getHeight();
            int radius;
            radius = 100;
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            canvas.drawPaint(paint);
            // Use Color.parseColor to define HTML colors
            paint.setColor(Color.parseColor("#CD5C5C"));
            canvas.drawCircle(x / 2, y / 2, radius, paint);
        }
     }
}

Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using

canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);

These two link also help

http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o

http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html


@Override
public void onDraw(Canvas canvas){
    canvas.drawCircle(xPos, yPos,radius, paint);
}

Above is the code to render a circle. Tweak the parameters to your suiting.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-canvas

How to draw circle by canvas in Android? Draw in Canvas by finger, Android Android Center text on canvas Android canvas draw rectangle Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView? Creating an empty bitmap and drawing though canvas in Android Drawable image on a canvas Measuring text height to be drawn on Canvas ( Android ) How to draw a filled triangle in android canvas? Android Canvas.drawText