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?
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).
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).
You can override the onDraw method of your view and draw the circle.
protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(x, y, radius, paint); }
For a better reference on drawing custom views check out the official Android documentation.
http://developer.android.com/training/custom-views/custom-drawing.html
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With