首页 > 解决方案 > Flutter:需要帮助来实现带有图像的卡片

问题描述

我需要实现类似于下图所示的设计:

在此处输入图像描述

标签: flutterflutter-layout

解决方案


这是使用 aCustomPainter和 Path 生成绘图的可能解决方案。我使用了 Path 类的cubicTo和 aaddRect函数。有关这些函数和路径绘制的更多信息,我参考了这篇:Flutter 中的路径:可视化指南

这是扩展的类CustomPainter

class CardPainter extends CustomPainter {
  final Color color;
  final double strokeWidth;

  CardPainter({this.color = Colors.black, this.strokeWidth = 3});

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = color
      ..strokeWidth = this.strokeWidth
      ..style = PaintingStyle.stroke;
    canvas.drawPath(getShapePath(size.width, size.height), paint);
  }

  // This is the path of the shape we want to draw
  Path getShapePath(double x, double y) {
    return Path()
      ..moveTo(2 * x / 3, y)
      ..cubicTo(x / 1.5, y, 0, y / 3, x, 0) // draw cubic curve
      ..addRect(Rect.fromLTRB(0, 0, x, y)); // draw rectangle
  }

  @override
  bool shouldRepaint(CardPainter oldDelegate) {
    return oldDelegate.color != color;
  }
}

这里是执行CustomPainter

class CustomCard extends StatelessWidget {
  CustomCard({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Custom Card Demo')),
      body: Center(
        child: Container(
          color: Colors.grey[300],
          width: 250,
          height: 120,
          padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: CustomPaint(
            painter: CardPainter(color: Colors.blueAccent, strokeWidth: 3), // this is your custom painter
            child: Stack(
              children: <Widget>[
                Positioned(
                  top: 25,
                  left: 30,
                  child: Text('Text1'),
                ),
                Positioned(
                  top: 55,
                  left: 150,
                  child: Text('Text2'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

推荐阅读