使用android中的画布通过旋转创建具有4个线段的圆

时间:2019-02-15 17:50:18

标签: android android-canvas android-graphics

我需要使用以下四种随机颜色创建一个分段圆:

http://vectips.com/wp-content/uploads/2015/04/39.png。 “一圈四段”

在参考有关使用canvas.drawArc()的android文档时,我做了以下代码,但它按我的期望工作,因为它只显示了一个片段。

           Bitmap bitMap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

    bitMap = bitMap.copy(bitMap.getConfig(), true);
    // Construct a canvas with the specified bitmap to draw into
    Canvas canvas = new Canvas(bitMap);
    // Create a new paint with default settings.
    Paint paint = new Paint();
    // smooths out the edges of what is being drawn
    paint.setAntiAlias(true);
    // set color
    paint.setColor(Color.BLUE);

    paint.setStrokeWidth(4.5f);


    RectF oval = new RectF(200F, 200F, 450F, 450F);

    paint.setStyle(Paint.Style.FILL);
    canvas.drawArc(oval, 0F, 90F, true, paint);
    paint.setColor(Color.GREEN);
    canvas.drawArc(oval, 90F, 90F, true, paint);
    paint.setColor(Color.RED);

    canvas.drawArc(oval, 180F, 90F, true, paint);
    paint.setColor(Color.BLACK);

    canvas.drawArc(oval, 270F, 90F, true, paint);

    imageView.setImageBitmap(bitMap);

1 个答案:

答案 0 :(得分:0)

您的弧角不正确。参见drawArc Canvas reference,角度参数如下:

  • startAngle-圆弧开始处的起始角度(以度为单位)

  • sweepAngle-顺时针测量的扫描角度(度)

您的最后一条弧线覆盖了所有先前的弧线。您应该执行以下操作(下面的Kotlin代码):

private val oval = RectF(200F, 200F, 450F, 450F)

private val paint = Paint()

override fun onDraw(canvas: Canvas) {
  paint.style = Paint.Style.FILL

  paint.color = Color.BLACK
  canvas.drawArc(oval, 0F, 90F, true, paint)
  paint.color = Color.BLUE
  canvas.drawArc(oval, 90F, 90F, true, paint)
  paint.color = Color.RED
  canvas.drawArc(oval, 180F, 90F, true, paint)
  paint.color = Color.GREEN
  canvas.drawArc(oval, 270F, 90F, true, paint)
}

会画出类似的东西

Sample output

Java版本:

  private RectF oval = new RectF(0F,0F,100F,100F);

  private Paint paint = new Paint();

  @Override
  protected void onDraw(Canvas canvas) {
    paint.setStyle(Paint.Style.FILL);

    paint.setColor(Color.BLACK);
    canvas.drawArc(oval, 0F, 90F, true, paint);
    paint.setColor(Color.BLUE);
    canvas.drawArc(oval, 90F, 1800F, true, paint)
    paint.setColor(Color.RED);
    canvas.drawArc(oval, 0F, 190F, true, paint)
    paint.setColor(Color.GREEN);
    canvas.drawArc(oval, 270F, 360F, true, paint)
  }