blob: 3d9fdd02ebaaf37b715ff7643b008af0cbcaedd8 [file] [log] [blame]
Hal Canary6c8422c2020-01-10 15:22:09 -05001// Copyright 2020 Google LLC.
2// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3#include "tools/fiddle/examples.h"
4REG_FIDDLE(SkPath_cubicTo_example_parametric, 512, 512, false, 0) {
5/*
6 If the starting point is (x0, y0), then this curve is defined as the
7 paramentric curve as `t` goes from 0 to 1:
8 s := 1 - t
9 x := (s * s * s * x0) +
10 (3 * s * s * t * x1) +
11 (3 * s * t * t * x2) +
12 (t * t * t * x3)
13 y := (s * s * s * y0) +
14 (3 * s * s * t * y1) +
15 (3 * s * t * t * y2) +
16 (t * t * t * y3)
17
18*/
19
20SkPoint cubic(SkPoint p0, SkPoint p1, SkPoint p2, SkPoint p3, float t) {
21 float s = 1 - t;
22 return {(s * s * s * p0.x()) + (3 * s * s * t * p1.x()) + (3 * s * t * t * p2.x()) +
23 (t * t * t * p3.x()),
24 (s * s * s * p0.y()) + (3 * s * s * t * p1.y()) + (3 * s * t * t * p2.y()) +
25 (t * t * t * p3.y())};
26}
27
28void draw(SkCanvas* canvas) {
29 canvas->clear(SkColorSetARGB(255, 255, 255, 255));
30 SkFont font(nullptr, 32);
31
32 SkPaint paint;
33 paint.setAntiAlias(true);
34 paint.setStyle(SkPaint::kStroke_Style);
35 paint.setStrokeWidth(5);
36
37 SkPoint a{136, 64};
38 SkPoint b{448, 448};
39 SkPoint c{64, 448};
40 SkPoint d{376, 64};
41
42 SkPath threeSegments;
43 threeSegments.moveTo(a);
44 threeSegments.lineTo(b);
45 threeSegments.lineTo(c);
46 threeSegments.lineTo(d);
47
48 canvas->drawPath(threeSegments, paint);
49
50 paint.setColor(SkColorSetARGB(255, 0, 0, 255));
51 SkPath cubicCurve;
52 cubicCurve.moveTo(a);
53 cubicCurve.cubicTo(b, c, d);
54 canvas->drawPath(cubicCurve, paint);
55
56 SkPaint textPaint;
57 textPaint.setColor(SkColorSetARGB(255, 0, 255, 0));
58 textPaint.setAntiAlias(true);
59 canvas->drawString("a", a.x(), a.y(), font, textPaint);
60 canvas->drawString("b", b.x(), b.y(), font, textPaint);
61 canvas->drawString("c", c.x() - 20, c.y(), font, textPaint);
62 canvas->drawString("d", d.x(), d.y(), font, textPaint);
63
64 SkPaint pointPaint;
65 pointPaint.setAntiAlias(true);
66 pointPaint.setStrokeWidth(8);
67 pointPaint.setStrokeCap(SkPaint::kRound_Cap);
68 pointPaint.setColor(SkColorSetARGB(255, 0, 255, 0));
69 const int N = 16;
70 for (int i = 0; i <= N; ++i) {
71 SkPoint p = cubic(a, b, c, d, (float)i / N);
72 canvas->drawPoint(p.x(), p.y(), pointPaint);
73 }
74 pointPaint.setColor(SkColorSetARGB(255, 255, 0, 0));
75}
76} // END FIDDLE