Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Circle at Center of Canvas

I'm just getting into basic drawing with Android. I'm starting off with a few simple shapes but I'm having a few issues. I'd like to draw a circle at the center of a canvas. I looked at a few examples but can't seem to make it work. I think it's because I don't really understand what variables go where.

Could someone please explain the proper way to draw my circle at the center of my screen. Here is my code:

public class Circle extends View{

int width = this.getWidth();
int height = this.getHeight();

public Circle(Context context) {
    super(context);
    setFocusable(true);

}
protected void onDraw(Canvas canvas){
    canvas.drawColor(Color.CYAN);
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    //canvas.drawCircle(100, 100, 50, paint);
    canvas.drawCircle(width/2, height/2, 100, paint);

    Display disp = ((WindowManager)this.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

    float radius = 0;//Radius caused an error so I initialized this variable

    canvas.drawCircle(disp.getWidth()/2, disp.getHeight()/2, radius, paint);

}

}

like image 927
David Avatar asked Mar 24 '23 23:03

David


1 Answers

width and height of the view have not been yet initialized when getWidth() and getHeight() are called, just use getWidth() and getHeight() in onDraw:

canvas.drawCircle(getWidth()/2, getHeight()/2, 100, paint);

You can also override onSizeChanged and get view width and height.

PS: do not create anything in onDraw, create the paint object in the constructor.

like image 114
Cédric Coulon Avatar answered Apr 05 '23 20:04

Cédric Coulon