在android画布中使用RectF创建一行3个圆圈(分段)

问题描述 投票:0回答:2

我想创建类似于这样的图形:https://cdn.business2community.com/wp-content/uploads/2017/01/pie-charts.png.png

我使用具有四种不同颜色的RectF创建了一个分段圆。下面是我的代码:

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

RectF oval = new RectF(10F, 5F, 45F, 5F);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.GRAY);
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);
canvas.rotate(43);
imageView.setImageBitmap(bitMap);

我想创建一个像这样的另外3个圆圈,但我无法得到它们,因为我无法识别确切的坐标。

android android-canvas android-graphics
2个回答
0
投票

你定义你的RectF的方式有一个问题,第二和第四个值是5f,这意味着RectF的宽度为0:public RectF(float left, float top, float right, float bottom)

如果你使你的矩形更大,你的代码将会起作用。


0
投票

您应该放在RectF构造函数中的坐标是相对于使用Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)创建位图时所放置的坐标。例如,使用100x100像素的位图,并以这种方式设置RectF

new RectF(5f, 10f, 85f, 75f);

您将得到以下结果(ImageView背景为蓝色以清楚地看到其边界):

enter image description here

如您所见,RectF的限制在位图坐标中设置,从左侧水平开始,从顶部垂直开始。

要创建三个饼图,您可以创建一个更大的位图(此处为300x100)并为每个新图表偏移RectF的坐标:

private fun drawPieCharts() {
    var bitMap = Bitmap.createBitmap(300, 100, Bitmap.Config.ARGB_8888)
    bitMap = bitMap.copy(bitMap.config, true)
    // Construct a canvas with the specified bitmap to draw into
    val canvas = Canvas(bitMap)

    drawSinglePie(canvas, 0f)
    drawSinglePie(canvas, 100f)
    drawSinglePie(canvas, 200f)

    imageView.setImageBitmap(bitMap)
}

private fun drawSinglePie(canvas: Canvas, horizontalOffset: Float) {
    val oval = RectF(5f + horizontalOffset, 10f, 85f + horizontalOffset, 75f)
    paint.style = Paint.Style.FILL
    paint.color = Color.GRAY
    canvas.drawArc(oval, 0f, 90f, true, paint)

    paint.color = Color.GREEN
    canvas.drawArc(oval, 90f, 90f, true, paint)

    paint.color = Color.RED
    canvas.drawArc(oval, 180f, 90f, true, paint)

    paint.color = Color.BLACK
    canvas.drawArc(oval, 270f, 90f, true, paint)
}

这会导致这个结果:

enter image description here

但是位图可能会像上面的屏幕截图一样被拉伸,因此更好的解决方案是创建自定义视图以避免这种像素化。

© www.soinside.com 2019 - 2024. All rights reserved.