如何在Flutter中使用CustomPainter只圆整一条线的一端?

ztmd8pv5  于 2023-01-31  发布在  Flutter
关注(0)|答案(1)|浏览(109)

我可以使用strokeCap属性将两端都更改为方形或圆形,但不知道如何为每一端应用定制的设置(即一端为圆形,另一端为方形)。
怎样才能达到这个效果呢?

import 'package:flutter/material.dart';

class LinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var height = size.height;
    var width = size.width;

    var paint = Paint()
      ..color = Colors.red
      ..strokeWidth = 20
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    var path = Path();

    path.moveTo(width * 0.25, height / 2);
    path.lineTo(width * 0.75, height / 2);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

class Example extends StatefulWidget {
  const Example({Key? key}) : super(key: key);

  @override
  State<Example> createState() => _ExampleState();
}

class _ExampleState extends State<Example> with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomPaint(
        painter: LinePainter(),
        child: Container(),
      ),
    );
  }
}
3ks5zfa0

3ks5zfa01#

没有现有的PaintingStyle或StrokeCap选项可用于仅设置一个端点,目前这两个端点的控制方式相同。
如果你只想在一端画圆帽,另一种方法是画一条没有圆帽的线,然后画一个圆与线的一端重叠

@override
void paint(Canvas canvas, Size size) {

    var height = size.height;
    var width = size.width;
    
    var thickness = 20;
    var capRadius = thickness * 0.5 ;

    //Line paint, is set to stroke
    var linePaint = Paint()
        ..color = Colors.red
        ..strokeWidth = thickness
        ..style = PaintingStyle.stroke
        ..strokeCap = StrokeCap.butt; //butt is default, no caps

    //Cap paint, is set to fill by default
    var capPaint = Paint()
        ..color = Colors.red;
        
    //Draw line
    var path = Path();
    path.moveTo(width * 0.25, height / 2);
    path.lineTo(width * 0.75, height / 2);
    canvas.drawPath(path, linePaint);
    
    //Draw cap
    canvas.drawCircle( Offset(width * 0.75, height / 2), capRadius, capPaint );
    
}

相关问题