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

}

}


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.


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


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

  • https://github.com/swapgo20/Android-Hand-Drawing
  • https://github.com/codepath/android_guides/wiki/Basic-Painting-with-Views
  • 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.

    链接地址: http://www.djcxy.com/p/68956.html

    上一篇: 在画布上绘制“洞”

    下一篇: 在画布中心画圈