Flutter CustomPaint 自定义信封分割线

2020-11-02  本文已影响0人  星邪Ara

效果图

image.png

直接上代码

import 'package:flutter/material.dart';

/// 信封分割线
class MailLineView extends StatelessWidget {
  final double height; //高度
  final double colorWidth; //颜色区域宽度
  final double emptyWidth; //间隔宽度

  MailLineView({this.height: 2, this.colorWidth: 8, this.emptyWidth: 8});

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: MailLinePainter(colorWidth: colorWidth, emptyWidth: emptyWidth),
      size: Size(double.infinity, height),
    );
  }
}

class MailLinePainter extends CustomPainter {
  final double colorWidth; //颜色区域宽度
  final double emptyWidth; //间隔宽度
  MailLinePainter({this.colorWidth: 8, this.emptyWidth: 8});

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..style = PaintingStyle.fill;

    double drawLength = 0;
    int count = 0;
    while (drawLength < size.width) {
      if (count != 0) drawLength += emptyWidth;
      /*设置paint的颜色*/
      if (count % 2 == 0) {
        paint.color = Color(0xFF5D8AD0);
      } else {
        paint.color = Color(0xFFD05D5D);
      }
      /*开始画多边形*/
      Path path = new Path();
      path.moveTo(drawLength, size.height); // 此点为多边形的起点
      path.lineTo(drawLength + colorWidth - size.height, size.height);
      path.lineTo(drawLength + colorWidth, 0);
      path.lineTo(drawLength + size.height, 0);
      path.close(); // 使这些点构成封闭的多边形
      canvas.drawPath(path, paint);
      drawLength += colorWidth;
      count++;
    }
  }

  ///有变化刷新
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

上一篇 下一篇

猜你喜欢

热点阅读