Flutter-使用customPainter在右下角绘制一个三角形

时间:2020-08-20 13:49:48

标签: flutter dart canvas

我正在尝试在页面右下方绘制一个三角形。
我已经成功地在左上角创建了一个,像这样:

    void paint(Canvas canvas, Size size) {

    // top left
    final pathOrange = Path();
    pathOrange.lineTo(0, size.height/3);
    pathOrange.lineTo(size.width/1.5, 0);
    pathOrange.close();
    canvas.drawPath(pathOrange, _paintOrange);
  }

但是我找不到右下角的方法。我已经读过canvas显然是默认设置为0,0的,但是我似乎无法实例化它两次,否则我会使用canvas.translate更改初始位置。
我知道左下角的坐标是0,size.height和右上角的size.width,0,但是我无法获得右下角的坐标。
那就是结果
end result
这就是我所做的
what I've done

3 个答案:

答案 0 :(得分:5)

首先,您需要做一些数学运算:

enter image description here

知道点的位置后,就可以画线了。

final pathOrange = Path();

// Create your line from the top left down to the bottom of the orange
pathOrange.lineTo(0, size.height * .3387);

// Create your line to the bottom right of orange
pathOrange.lineTo(size.width, size.height * .162);

// Create your line to the top right corner
pathOrange.lineTo(size.width, 0); // 0 on the Y axis (top)

// Close your line to where you started (0,0)
pathOrange.close();

// Draw your path
canvas.drawPath(pathOrange, _paintOrange);

现在,再加上以下内容重复这些步骤:moveTo。默认情况下,您的路径将从左上角的原点(0,0)开始。但是,您希望它从新位置开始。

final pathGreen = Path();

// Create your line from the top left down to the bottom of the orange
pathGreen.moveTo(0, size.height * .978); // (100 - 2.8) / 100

// Create your line to the bottom left
pathGreen.lineTo(0, size.height);

// Create your line to the bottom right
pathGreen.lineTo(size.width, size.height); 

// Create your line to top right of green
pathGreen.lineTo(size.width, size.height * .6538); // (100 - 34.62) / 100

// Close your line to where you started
pathGreen.close();

// Draw your path
canvas.drawPath(pathGreen, _paintGreen);

答案 1 :(得分:1)

也许您可以尝试这样的事情?

final pathBlue = Path();
pathBlue.moveTo(size.width, size.height);
pathBlue.lineTo(size.width, (size.height/3)*2);
pathBlue.lineTo(0, size.height);
pathBlue.close();
canvas.drawPath(pathBlue, _paintBlue);

答案 2 :(得分:1)

您可以轻松添加另一个路径对象,然后使用画布再次绘制它。

@override
  void paint(Canvas canvas, Size size) {
    final paintOrange = Paint()..color = Colors.orange;
    final paintGreen = Paint()..color = Colors.green;

    final pathOrange = Path();
    pathOrange.lineTo(0, size.height / 3);
    pathOrange.lineTo(size.width, 0);
    pathOrange.close();

    final pathGreen = Path();
    pathGreen.moveTo(size.width, size.height);
    pathGreen.lineTo(0, size.height);
    pathGreen.lineTo(size.width, size.height / 1.5);
    pathGreen.close();

    canvas.drawPath(pathOrange, paintOrange);
    canvas.drawPath(pathGreen, paintGreen);
  }