颤振自定义矩形

时间:2020-06-02 14:26:45

标签: flutter dart

如何在Flutter中使用CustomPainter类来绘制类似下面的内容?

enter image description here

忽略中间的“批量”标签。我只想实现在边框线之间使用空格的边框/框形状。

1 个答案:

答案 0 :(得分:1)

尝试一下

您可以在Github

上进行检查

或者在DartPad上尝试

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ScanPainter(
            size: 200,
            color: Colors.grey,
          ),
        ),
      ),
    );
  }
}

class ScanPainter extends StatelessWidget {
  final double size;
  final Color color;

  ScanPainter({
    @required this.size,
    this.color = Colors.grey,
  }) : assert(size != null);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: size,
      width: size,
      child: Stack(
        children: [
          Positioned(
            top: 0.0,
            left: 0.0,
            child: _buildRotatedPart(
              0,
              size * .2,
            ),
          ),
          Positioned(
            top: 0.0,
            right: 0.0,
            child: _buildRotatedPart(
              1.5708,
              size * .2,
            ),
          ),
          Positioned(
            bottom: 0.0,
            right: 0.0,
            child: _buildRotatedPart(
              3.14159,
              size * .2,
            ),
          ),
          Positioned(
            bottom: 0.0,
            left: 0.0,
            child: _buildRotatedPart(
              4.71239,
              size * .2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRotatedPart(double radians, double size) {
    return Transform.rotate(
      angle: radians,
      child: CustomPaint(
        painter: ScanCustomPainter(color: this.color),
        size: Size(size, size),
      ),
    );
  }
}

class ScanCustomPainter extends CustomPainter {
  final Color color;

  ScanCustomPainter({
    @required this.color,
  }) : assert(color != null);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()..color = this.color;
    var path = Path();
    double baseHeight = size.height;
    double baseWidth = size.width;

    path.moveTo(0, baseHeight);
    path.lineTo(0, baseHeight * .5);
    path.quadraticBezierTo(0, 0, baseWidth * .5, 0);
    path.lineTo(baseWidth, 0);
    path.lineTo(baseWidth, baseHeight * .3);
    path.lineTo(baseWidth * .6, baseHeight * .3);
    path.quadraticBezierTo(
        baseWidth * .3, baseHeight * .3, baseWidth * .3, baseHeight * .6);
    path.lineTo(baseWidth * .3, baseHeight);

    path.close();

    canvas.drawPath(path, paint);
  }

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