如何在Android中绘制Bezier曲线

时间:2015-05-06 10:09:33

标签: android android-canvas bezier best-fit-curve

我需要在项目中创建贝塞尔曲线。为了这个目的,我正在用油漆绘制一个视图,但问题是我没有得到我需要的确切形状,如下图所示。所以请帮助我解决我的代码中的解决方案和更改或修改。提前谢谢。

用于创建Bezier曲线的代码:

public class DrawView extends View {

    public DrawView (Context context) {
        super (context);
    }

    protected void onDraw (Canvas canvas) {
        super.onDraw (canvas);

        Paint pLine = new Paint () {{
            setStyle (Paint.Style.STROKE);
            setAntiAlias (true);
            setStrokeWidth (1.5f);
            setColor (Color.RED); // Line color
        }};

        Paint pLineBorder = new Paint () {{
            setStyle (Paint.Style.STROKE);
            setAntiAlias (true);
            setStrokeWidth (3.0f);
            setStrokeCap (Cap.ROUND);
            setColor (Color.RED); // Darker version of the color
        }};
        Path p = new Path ();
        Point mid = new Point ();
        // ...
        Point start =new Point (30,90);
        Point end =new Point (canvas.getWidth ()-30,140);
        mid.set ((start.x + end.x) / 2, (start.y + end.y) / 2);

        // Draw line connecting the two points:
        p.reset ();
        p.moveTo (start.x, start.y);
        p.quadTo ((start.x + mid.x) / 2, start.y, mid.x, mid.y);
        p.quadTo ((mid.x + end.x) / 2, end.y, end.x, end.y);

        canvas.drawPath (p, pLineBorder);
        canvas.drawPath (p, pLine);
    }
}

MainActivity

public class MainActivity extends Activity {

    private DrawView drawView;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        drawView = new DrawView (this);
        setContentView (drawView);

    }
}

我的实际需求:

enter image description here

我得到的输出:

enter image description here

2 个答案:

答案 0 :(得分:18)

经过长时间的努力,我从头开始找到了我的问题的根本原因。 感谢帮助我生成坐标的tool以及blog ,它向我展示了我需要的确切样本。最后我的代码如下:

public class DrawView extends View {

    Paint paint;
    Path path;

    public DrawView(Context context) {
        super(context);
        init();
    }

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

    public DrawView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init(){
        paint = new Paint();

        paint.setStyle(Paint.Style.STROKE);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        path = new Path();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(3);
        path.moveTo(34, 259);
        path.cubicTo(68, 151, 286, 350, 336, 252);
        canvas.drawPath(path, paint);

    }

答案 1 :(得分:0)

您尚未关闭路径,也没有为绘画设置颜色。