首页 > 解决方案 > 如何在 Flutter 中绘制自定义背景?

问题描述

鲁

我需要画出上面的背景。我无法绘制黑色和蓝色背景。

class _BackGroundPainter extends CustomPainter{
  @override
  void paint(Canvas canvas, Size size) {
    Path path = Path();
    Paint paint = Paint();

    path.moveTo(0, size.height*0.2);

    path.quadraticBezierTo(size.width * 0.135, size.height * 0.178, size.width * 0.281, size.height*0.0889);
    path.quadraticBezierTo(size.width * 0.4, size.height * 0.0113, size.width*0.8, 0);
    path.lineTo(0, 0);
    path.lineTo(0, size.width*0.8);
    path.close();
    paint.color = Colors.yellowAccent;
    canvas.drawPath(path, paint);

    path = Path();
    path.moveTo(0, size.height * 0.4);

    path.quadraticBezierTo(size.width*0.4, size.height * 0.5, size.width*0.6, size.height*0.25);

    path.quadraticBezierTo(size.width*0.7, size.height*0.15, size.width, size.height*0.1);

    path.lineTo(0, 0);
    paint.color = Colors.black87;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

这是我的代码,我只能画黄线

标签: flutterflutter-layout

解决方案


为此,您可以将CustomPainterCanvas类一起使用。正如@Farhana 建议的那样,您可以使用图像,但该方法有一些缺点

  • 内存昂贵

  • 不可扩展

  • ...

这是从官方文档中绘制天空背景的示例

class Sky extends CustomPainter {


@override
  void paint(Canvas canvas, Size size) {
    var rect = Offset.zero & size;
    var gradient = RadialGradient(
      center: const Alignment(0.7, -0.6),
      radius: 0.2,
      colors: [const Color(0xFFFFFF00), const Color(0xFF0099FF)],
      stops: [0.4, 1.0],
    );
    canvas.drawRect(
      rect,
      Paint()..shader = gradient.createShader(rect),
    );
  }

  @override
  SemanticsBuilderCallback get semanticsBuilder {
    return (Size size) {
      var rect = Offset.zero & size;
      var width = size.shortestSide * 0.4;
      rect = const Alignment(0.8, -0.9).inscribe(Size(width, width), rect);
      return [
        CustomPainterSemantics(
          rect: rect,
          properties: SemanticsProperties(
            label: 'Sun',
            textDirection: TextDirection.ltr,
          ),
        ),
      ];
    };
  }
  @override
  bool shouldRepaint(Sky oldDelegate) => false;
  @override
  bool shouldRebuildSemantics(Sky oldDelegate) => false;
}

推荐阅读