如何在安卓中用画布画圈?

2022-08-31 13:18:50

我想用画布画圆圈。这是我的代码:

[我的活动.java]:

public class MyActivity extends Activity 
{
 public void onCreate(Bundle savedInstanceState) 
   {
      ...
      setContentView(new View(this,w,h));
   }
        
}

[查看.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);
    }
}

所以我只有黑屏,没有圆圈。为什么它不起作用?如何解决?


答案 1

您可以覆盖视图的 onDraw 方法并绘制圆。

protected void onDraw(Canvas canvas) {
 super.onDraw(canvas);

 canvas.drawCircle(x, y, radius, paint);

}

有关绘制自定义视图的更好参考,请查看官方Android文档。

http://developer.android.com/training/custom-views/custom-drawing.html


答案 2
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);
        }
     }
}

如果要在中心绘制圆圈,请进行编辑。您还可以将整个画布平移到中心,然后在中心处绘制圆圈。

canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);

这两个链接也有所帮助

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


推荐