Flutter 如何画半圆(半圆)

Dol*_*rma 14 flutter flutter-layout

我怎样才能画这样的半圆?

在此处输入图片说明

代码:

class DrawHalfCircleClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final Path path = new Path();
    ...
    return path;
  }
  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return true;
  }
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 19

创建一个接受 a的StatelessWidgetsay 。MyArcdiameter

class MyArc extends StatelessWidget {
  final double diameter;

  const MyArc({Key key, this.diameter = 200}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: MyPainter(),
      size: Size(diameter, diameter),
    );
  }
}

// This is the Painter class
class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = Colors.blue;
    canvas.drawArc(
      Rect.fromCenter(
        center: Offset(size.height / 2, size.width / 2),
        height: size.height,
        width: size.width,
      ),
      math.pi,
      math.pi,
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
Run Code Online (Sandbox Code Playgroud)

用法:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(),
    body: MyArc(diameter: 300),
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要在“Paint”对象上使用“Shader”。 (2认同)

小智 11

Container(
    decoration: const BoxDecoration(
      color: Colors.black,
      borderRadius: BorderRadius.only(
        bottomLeft: Radius.circular(100),
        bottomRight: Radius.circular(100),
      ),
Run Code Online (Sandbox Code Playgroud)

使用此代码,您可以制作一个半圆。


小智 5

创建一个从 CustomClipper 扩展的类,并使用 arcToPoint 方法来绘制圆并使用 ClipPath 小部件,下面是实现该功能的代码

ClipPath(
      clipper: CustomClip(),
      child: Container(
        width: 200,
        height: 100,
        color: Colors.blue,
      ),
    ),
Run Code Online (Sandbox Code Playgroud)
    class CustomClip extends CustomClipper<Path> {
      @override
      Path getClip(Size size) {
        double radius = 100;
    
        Path path = Path();
        path
          ..moveTo(size.width / 2, 0)
          ..arcToPoint(Offset(size.width, size.height),
              radius: Radius.circular(radius))
          ..lineTo(0, size.height)
          ..arcToPoint(
            Offset(size.width / 2, 0),
            radius: Radius.circular(radius),
          )
          ..close();
    
        return path;
      }
    
      @override
      bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
        return true;
      }
    }
Run Code Online (Sandbox Code Playgroud)