flutter 四角圆角实现

215 阅读1分钟

自定义组件代码:

import 'package:flutter/material.dart';

/// 四个角圆角
class BorderPainter extends CustomPainter {

  double radius;
  double? strokeWidth;
  Color? color;

  BorderPainter({
    required this.radius,
    this.strokeWidth,
    this.color
  }) : super();

  @override
  void paint(Canvas canvas, Size size) {
    double sh = size.height; 
    double sw = size.width; 
    double cornerSide = radius;

    Paint paint = Paint()
      ..color = color ?? Colors.black
      ..strokeWidth = strokeWidth ?? 1.5
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    Path path = Path()
      ..moveTo(cornerSide + 4, 0)
      ..lineTo(cornerSide, 0)
      ..quadraticBezierTo(0, 0, 0, cornerSide)
      ..lineTo(0, cornerSide + 4)
      ..moveTo(0, sh - cornerSide - 4)
      ..lineTo(0, sh - cornerSide)
      ..quadraticBezierTo(0, sh, cornerSide, sh)
      ..lineTo(cornerSide + 4, sh)
      ..moveTo(sw - cornerSide - 4, sh)
      ..lineTo(sw - cornerSide, sh)
      ..quadraticBezierTo(sw, sh, sw, sh - cornerSide)
      ..lineTo(sw, sh - cornerSide - 4)
      ..moveTo(sw, cornerSide + 4)
      ..lineTo(sw, cornerSide)
      ..quadraticBezierTo(sw, 0, sw - cornerSide, 0)
      ..lineTo(sw - cornerSide - 4, 0);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(BorderPainter oldDelegate) => false;

  @override
  bool shouldRebuildSemantics(BorderPainter oldDelegate) => false;
}

使用方式:

CustomPaint(
  foregroundPainter:
      BorderPainter(radius: 4, color: Colors.blue, strokeWidth: 2),
  child: Container(
    decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(4)),
        color: Colors.transparent),
    width: 100,
    height: 100,
  ),
),

效果图:

f04d0f5fd3a74c6ca58d10fa80d232ab.png