4

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);

}

}

David
  • 501
  • 3
  • 10
  • 30
  • 2
    I don't know much about android programming, but I do know that a radius of 0 means you don't have a circle. http://en.wikipedia.org/wiki/Radius – Kevin May 14 '13 at 20:21
  • possible duplicate of [Draw Circle on touch](http://stackoverflow.com/questions/11796357/draw-circle-on-touch) – bummi Feb 01 '15 at 15:51

3 Answers3

8

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.

0

public void drawCircle(Graphics2D g, int x, int y, int radius) {

x = x-(radius/2);

y = y-(radius/2);

g.fillOval(x,y,radius,radius);

}

here x,y is the position of canvas where you want to draw circle and you can find it with motion listener if you want to set x,y position dynamically hope this will help you

Ajay Pandya
  • 2,417
  • 4
  • 29
  • 65
-1

There are some links which are very useful for us and I hope they will work for you and other.

  1. https://github.com/swapgo20/Android-Hand-Drawing
  2. https://github.com/codepath/android_guides/wiki/Basic-Painting-with-Views
  3. https://github.com/Korilakkuma/CanvasView

I hope above links are very useful to draw shapes on canvas.

I suggest you use third link and use only Path class (http://developer.android.com/reference/android/graphics/Path.html) of android to draw shapes.

ddarellis
  • 3,912
  • 3
  • 25
  • 53
Yogendra
  • 4,817
  • 1
  • 28
  • 21