Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to draw a circle on Canvas using java for android [duplicate]

I want to draw a circle on a canvas in my android app. I searched a lot and realized if I need a dynamic form of painting which can be updated time by time I need to use canvas instead of imageView.

any help is appreciated

this is the code that I wrote so far but it will not draw anything on the android device screen:

    private void createBitMap() {
    Bitmap bitMap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);  //creates bmp
    bitMap = bitMap.copy(bitMap.getConfig(), true);     //lets bmp to be mutable
    Canvas canvas = new Canvas(bitMap);                 //draw a canvas in defined bmp

    Paint paint = new Paint();                          //define paint and paint color
    paint.setColor(Color.RED);
    paint.setStyle(Style.FILL_AND_STROKE);
    //paint.setAntiAlias(true);

    canvas.drawCircle(50, 50, 10, paint);
}
like image 240
Hossein Dolatabadi Avatar asked Dec 19 '13 03:12

Hossein Dolatabadi


People also ask

How do you draw a circle on a Canvas?

To draw arcs or circles, we use the arc() or arcTo() methods. Draws an arc which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction indicated by counterclockwise (defaulting to clockwise).

Can we draw directly on Canvas in android studio?

The parameter to onDraw() is a Canvas object that the view can use to draw itself. The Canvas class defines methods for drawing text, lines, bitmaps, and many other graphics primitives. You can use these methods in onDraw() to create your custom user interface (UI).


Video Answer


1 Answers

Update your createBitMap method like this

private void createBitMap() {
        // Create a mutable bitmap
        Bitmap bitMap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

        bitMap = bitMap.copy(bitMap.getConfig(), true);
        // Construct a canvas with the specified bitmap to draw into
        Canvas canvas = new Canvas(bitMap);
        // Create a new paint with default settings.
        Paint paint = new Paint();
        // smooths out the edges of what is being drawn
        paint.setAntiAlias(true);
        // set color
        paint.setColor(Color.BLACK);
        // set style
        paint.setStyle(Paint.Style.STROKE);
        // set stroke
        paint.setStrokeWidth(4.5f);
        // draw circle with radius 30
        canvas.drawCircle(50, 50, 30, paint);
        // set on ImageView or any other view 
        imageView.setImageBitmap(bitMap);

    }
like image 67
Jitender Dev Avatar answered Sep 27 '22 21:09

Jitender Dev