Paint.setStrokeJoin不适用于canvas.drawLines

时间:2019-03-19 16:59:00

标签: android canvas

我正在尝试使用canvas.drawLines(...)绘制折线图,​​但是看来折线没有正确连接。据我了解,使用Paint.setStrokeJoin应该使用斜接:

chartLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
chartLinePaint.setStyle(Paint.Style.STROKE);
chartLinePaint.setStrokeJoin(Paint.Join.MITER);
chartLinePaint.setStrokeWidth(6.0f);

如何解决此问题并使线正确连接?

enter image description here

2 个答案:

答案 0 :(得分:2)

问题

  

您可能已经在Android文档中注意到,您无法申请   drawLine的样式。

ref

Canvas documentation

  

drawLine:

public void drawLine (float startX, float startY, float stopX, float stopY, Paint paint)
     

绘制具有指定的起点和终点x,y坐标的线段,   使用指定的涂料。

     

请注意,由于行始终为“框架”,因此样式在   油漆。

     

将不会绘制简并线(长度为0)。

     

drawLines:

public void drawLines (float[] pts, int offset, int count, Paint paint)
     

画一系列线。每行取自4个连续值   在pts数组中。因此,要绘制1条线,数组必须至少包含   4个值。 在逻辑上与绘制数组相同为   如下:

drawLine(pts[0], pts[1], pts[2], pts[3]) 
followed by:
drawLine(pts[4], pts[5], pts[6], pts[7])
     

以此类推。

     

解决方案

     

如果您需要应用style,解决方案是改为使用drawPath。   它将应用style对象中设置的paint

答案 1 :(得分:2)

正如我在评论中告诉您的那样,Paint对象仅在用Path绘制时才完全应用。

drawLine文档中有一个段落,其中包含:'样式在绘画中被忽略',并且同一内容应用于drawLines方法。

为了对此进行测试,我创建了一个简单的自定义视图:

class CanvasTestView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val textPaint1 = Paint(ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.MITER
        strokeWidth = 12.0f
        color = Color.RED
    }

    private val textPaint2 = Paint(ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.MITER
        strokeWidth = 12.0f
        color = Color.BLUE
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        canvas?.apply {

            val floatArray = floatArrayOf(250f, 550f, 450f, 200f, 450f, 200f, 650f, 700f)
            drawLines(floatArray, textPaint2)

            val path = Path()
            path.moveTo(200f, 500f)
            path.lineTo(400f, 200f)
            path.lineTo(600f, 700f)
            drawPath(path, textPaint1)
        }

    }
}

结果是这样的:

enter image description here

因此,使用drawLines部分应用Paint obj的样式(例如颜色),而不应用strokeJoin类似的属性。 drawPath似乎全部应用了。

如果您遇到性能问题,则可以尝试将结果缓存到某个位置,预先计算动画或尝试使用更简单的动画。

  

请记住,如果您没有特殊要求,   很棒的库:MPAndroidChart,它已经具有一些内置动画

相关问题