4

我刚开始接触自定义画家,我已经创建了一个基本的十字架,但不知道如何使角落变圆并使颜色成为渐变?

似乎需要一个渐变createShaderrect但我没有,因为我使用了路径。

我也想把十字架的拐角弄圆一点,但不知道是怎么做的。我考虑过创建矩形,但似乎也无法创建倾斜的矩形。

class CrossPainter extends CustomPainter {
  CrossPainter({this.bodyColour, this.strokeColour, this.stroke});
  final Color bodyColour;
  final Color strokeColour;
  final double stroke;
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint
      ..color = strokeColour
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeWidth = stroke;

    Paint paint1 = Paint();
    paint1
      ..color = bodyColour
      ..style = PaintingStyle.fill
      ..strokeWidth = 0;

    double width = size.width;
    double height = size.height;

    Path path = Path();
    path.addPolygon([Offset.zero, Offset(width / 4, 0), Offset(width, height), Offset(width - (width / 4), height)], true);
    Path path2 = Path();
    path2.addPolygon(
        [Offset(width, 0), Offset(width - (width / 4), 0), Offset(0, height), Offset(0 + (width / 4), height)], true);

    canvas.drawPath(path, paint1);
    canvas.drawPath(path2, paint1);
    // canvas.drawPath(path, paint); //border
    // canvas.drawPath(path2, paint); //border
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

我也有paint1它添加了一个边框,但它看起来不太好,因为每个多边形都是一个单独的对象。

4

1 回答 1

0

您可以在 Shader 上自由使用 Rect 来填充画布上绘制的圆角多边形上的渐变。在我的方法中,我使用画布上定义的大小作为 Rect 的基础。

Paint()
  ..style = PaintingStyle.stroke
  ..strokeCap = StrokeCap.round
  ..shader = gradient
      .createShader(Rect.fromLTWH(0.0, 0.0, size.width, size.height))
  ..strokeWidth = 20,

然后,您可以将此绘制对象添加到您正在渲染的画布上。

至于渐变,您可以随意定义它。但这里有一个例子。

const Gradient gradient = SweepGradient(
  startAngle: 1.25 * math.pi / 2,
  endAngle: 5.5 * math.pi / 2,
  tileMode: TileMode.repeated,
  colors: <Color>[
    Colors.blueAccent,
    Colors.lightBlueAccent,
  ],
);
于 2022-02-03T07:30:30.143 回答