自定义画笔无法正常工作。出现白屏

时间:2020-10-13 22:43:26

标签: flutter dart flutter-layout flutter-test

我想使用CustomPainter()创建背景设计,但在模拟器上却出现白屏。

我尝试使用Scaffold()将紫色用作backgroundColor,它可以工作,但无法使用CustomPainter获得任何东西。

我的代码:

import 'package:flutter/material.dart';

void main() => runApp(
  MaterialApp(
    debugShowCheckedModeBanner: false,
    home: Background()));

class Background extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomPaint(painter: PurplePainter()));
  }
}
class PurplePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final height = size.height;
    final width = size.width;
    Paint paint = Paint();
    Path mainBackground = Path();
    mainBackground.addRect(Rect.fromLTRB(0, 0, width, height));
    paint.color=Colors.purple.shade700;
    canvas.drawPath(mainBackground, paint);

    Path arcCreator = Path();
    arcCreator.moveTo(0, height*0.2);
    arcCreator.quadraticBezierTo(width*0.45, height*0.25, width*0.5, height*0.5);
    arcCreator.quadraticBezierTo(width*0.5, height*0.5, width*0.1, height);
    paint.color=Colors.purple.shade600;
    canvas.drawPath(arcCreator, paint);
  }

  @override
  bool shouldRepaint(PurplePainter oldDelegate){
    return oldDelegate != this;
  }
}

你能帮我吗?

1 个答案:

答案 0 :(得分:0)

CustomPaint小部件上,您可以传递sizepainter以便将其呈现在屏幕上。 size的默认CustomPaint0.0。在您的电脑中,您只有一个painter,但没有给它size。您可以通过size参数或child小部件来提供它。只需执行以下操作即可:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomPaint(
        size: MediaQuery.of(context).size, //add this part
        painter: PurplePainter()),
    );
  }