Home > Back-end >  How to round just one end of a line using CustomPainter in Flutter?
How to round just one end of a line using CustomPainter in Flutter?

Time:01-30

I can change both ends to square or rounded using the strokeCap property but can't figure out how to apply tailored settings for each end (ie one end rounded and one square).

How can I achieve this effect?

example here


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(),
      ),
    );
  }
}

CodePudding user response:

There is no existing PaintingStyle or StrokeCap option for setting only one cap, currently both caps are controlled the same.

If you just want the rounded cap at one end, an alternative would be to draw the line with no caps, then draw a circle overlapping the end. This would only work for solid colors though.

@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 );
    
}
  • Related