如何在flutter中将路径剪切为弯曲的导航栏的圆形路径

时间:2020-02-27 19:43:27

标签: flutter flutter-layout

我在flutter项目中使用的是Curved Navigation Bar。但与我想要的不完全相同。任何人都可以像所附图片一样将其剪切到精确的圆形吗? 这是剪辑路径代码。

class NavCustomPainter extends CustomPainter {
double loc;
double s;
Color color;
TextDirection textDirection;

NavCustomPainter(
  double startingLoc, int itemsLength, this.color, this.textDirection) {
final span = 1.0 / itemsLength;
s = 0.2;
double l = startingLoc + (span - s) / 2;
loc = textDirection == TextDirection.rtl ? 0.8 - l : l;
}

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

final path = Path()
  ..moveTo(0, 0)
 ..lineTo((loc + 0.0) * size.width, 0)
  ..lineTo((loc + 0.015) * size.width, 0)
  ..cubicTo(
    (loc + s * 0.05) * size.width,
    size.height * 0.07,
    loc * size.width,
    size.height * 0.65,
    (loc + s * 0.50) * size.width,
    size.height * 0.65,
  )
  ..cubicTo(
    (loc + s + 0.01) * size.width,
    size.height * 0.65,
    (loc + s - s * 0.1) * size.width,
    size.height * 0.07,
    (loc + s - 0.01) * size.width,
    0,
  )
  ..lineTo(size.width, 0)
  ..lineTo(size.width, size.height)
  ..lineTo(0, size.height)
  ..close();
canvas.drawPath(path, paint);

}

what i have

What I want

1 个答案:

答案 0 :(得分:0)

建议您不要使用自己的绘画,而应该使用Flutter库中开箱即用的形状。

看看这个利用CircularNotchedRectangle形状的示例:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Sample Code'),
    ),
    body: Center(
      child: Text('You have pressed the button $_counter times.'),
    ),
    bottomNavigationBar: BottomAppBar(
      shape: const CircularNotchedRectangle(),
      child: Container(height: 50.0,),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: _incrementCounter,
      tooltip: 'Increment Counter',
      child: Icon(Icons.add),
    ),
    floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
  );
}
}

哪个会产生以下输出:

Example

您可以自定义形状以实现所需的精确输出。您甚至可以使用CircularNotchedRectangle.getOuterPath来获得Path,该use std::any::TypeId; let is_little_endian = TypeId::of::<byteorder::NativeEndian>() == TypeId::of::<byteorder::LittleEndian>(); 描述具有平滑圆形凹口的矩形,并根据需要对其进行修改。