如何在 android 中的 canvas 上绘制折线?

How can I draw a polyline on a canvas in android?

我一直在尝试在 canvas 上画一条折线。我的代码没有错误,但是线段的连接序列不对 showing.Please 查找下面的代码片段;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;

public class MyView extends View {
    private Paint redPaint;

    public MyView(Context context) {
        super(context, null);
        redPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        redPaint.setStyle(Paint.Style.STROKE);
        redPaint.setColor(0xffff0000);
        redPaint.setStrokeWidth(5);

    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawRect(10,30,200,200,redPaint);
        canvas.drawCircle(300,300,250,redPaint);

        Path mylines=new Path();
        mylines.moveTo(0,0);
        mylines.lineTo(1,1);
        mylines.lineTo(2,2);
        mylines.lineTo(3,3);
        mylines.lineTo(4,4);
        Paint GreenPaint=new Paint();
        GreenPaint.setARGB(255,0,255,0);
        canvas.drawPath(mylines,GreenPaint);

    }
}

您的代码基本正确。您没有像 redPaint 那样完全初始化 GreenPaint,这是一个问题。第二个问题,虽然它可能不是问题,但你的折线形状太小了,即使完全初始化 GreenPaint,你也可能会错过它。

这是您的自定义视图的更新版本,其中包含一个额外的构造函数和一个已初始化的 greenPaint。我还更改了折线的形状并使其变大以便于查看 - 它只是您代码中的一个斑点。此外,我将对象分配移出 onDraw()

    public class MyView extends View {
    Path mylines = new Path();
    private Paint redPaint;
    private Paint greenPaint;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyView(Context context) {
        super(context, null);
        init();
    }

    private void init() {
        redPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        redPaint.setStyle(Paint.Style.STROKE);
        redPaint.setColor(0xffff0000);
        redPaint.setStrokeWidth(5);

        greenPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        greenPaint.setStyle(Paint.Style.STROKE);
        greenPaint.setARGB(255, 0, 255, 0);
        greenPaint.setStrokeWidth(5);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawRect(10, 30, 200, 200, redPaint);
        canvas.drawCircle(300, 300, 250, redPaint);

        mylines.moveTo(0, 0);
        mylines.lineTo(200, 50);
        mylines.lineTo(300, 150);
        mylines.lineTo(400, 250);
        mylines.lineTo(500, 300);

        canvas.drawPath(mylines, greenPaint);

    }
}

这里是显示。 (我为视图的可见性添加了灰色背景,但这不是必需的。)