Container의 형태를 변형하는 방법 여러 가지 메모

10283 단어 DartFlutter

하고 싶은 일



아래와 같은 라벨을 만들고 싶다.


CustomPaint를 사용한 방법



main.dart
Container(
  child: CustomPaint(
    painter: _TrianglePainter(),
    child: Container(
      padding: EdgeInsets.all(5),
      child: Text(
        "Label One",
        style: TextStyle(color: Colors.white),
      ),
    ),
  ),
),

class _TrianglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint();

    paint.color = Colors.blue;
    var path = Path();
    path.moveTo(0, 0);
    path.lineTo(size.width, 0);
    path.lineTo(size.width + 15, size.height / 2);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.lineTo(0, 0);
    path.close();
    canvas.drawPath(path, paint);
  }

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

ShapeDecoration을 사용한 예



main.dart
Container(
  padding: EdgeInsets.all(5),
  child: Text("Label Two", style: TextStyle(color: Colors.white)),
  decoration: ShapeDecoration(
    color: Colors.deepOrange,
    shape: _TagShape(),
))

class _TagShape extends ShapeBorder {
  @override
  EdgeInsetsGeometry get dimensions {
    return const EdgeInsets.only();
  }

  @override
  Path getInnerPath(Rect rect, {TextDirection textDirection}) {
    return getOuterPath(rect, textDirection: textDirection);
  }

  @override
  Path getOuterPath(Rect rect, {TextDirection textDirection}) {
    return Path()
      ..moveTo(rect.left, rect.top)
      ..lineTo(rect.left, rect.bottom)
      ..lineTo(rect.right, rect.bottom)
      ..lineTo(rect.right + 15, rect.top + rect.height / 2)
      ..lineTo(rect.right, rect.top)
      ..lineTo(rect.left, rect.top)
      ..close();
  }

  @override
  void paint(Canvas canvas, Rect rect, {TextDirection textDirection}) {}

  @override
  ShapeBorder scale(double t) {
    return null;
  }
}

좋은 웹페이지 즐겨찾기