如何使用 DashPathEffect 绘制等距破折号

Per*_*abs 3 geometry android

目前我正在使用带有硬编码间隔的 DashPathEffect 来绘制一个圆圈,如下所示:

float[] intervals = new float[]{ 3, 18 };
DashPathEffect path = new DashPathEffect(intervals, 0); 
paint.setPathEffect(path);
… … … …
canvas.drawCircle(x, y, radius, paint);
Run Code Online (Sandbox Code Playgroud)

但这会在圆圈的起点和终点处产生一个非等距的破折号,如下图所示:

在此处输入图片说明

我当然可以手动调整它,但这仅适用于一种特定的设备密度,并在不同的显示密度下再次产生相同的问题。计算等距破折号的公式是什么?

Ben*_* P. 7

You need n dashes plus n gaps to have the same total length as the circumference of the circle. The below code assumes you've correctly determined both the center point and the radius you want to use.

double circumference = 2 * Math.PI * radius;
float dashPlusGapSize = (float) (circumference / NUM_DASHES);
intervals[0] = dashPlusGapSize * DASH_PORTION;
intervals[1] = dashPlusGapSize * GAP_PORTION;

DashPathEffect effect = new DashPathEffect(intervals, 0);
paint.setPathEffect(effect);

canvas.drawCircle(center, center, radius, paint);
Run Code Online (Sandbox Code Playgroud)

For instance, I've used NUM_DASHES = 20, DASH_PORTION = 0.75f, and GAP_PORTION = 0.25f, and I see:

在此处输入图片说明

You can use different values for these constants to change how many dashes you chop the cirlce into, or how big the dash/gap are relative to each other (as long as DASH_PORTION + GAP_PORTION adds up to 1).