Shruti Ramnandan Sharma
Shruti Ramnandan Sharma

Reputation: 4565

How to draw a ring with CustomPainter in flutter?

I'm trying to draw a half ring with CustomPainter class, which you can see in the below image (which is in light purple & light orange colours) but unable to drawn it. I can just only draw circle, square and line.

Code:

class MakeCircle extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = Colors.white12;
    var position = Offset(size.width /10, size.height / 10);
    canvas.drawCircle(position, 40.0, paint);
  }
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

this can only draw circle.

enter image description here

Upvotes: 2

Views: 5060

Answers (1)

Taleb
Taleb

Reputation: 2259

you must use PaintingStyle.stroke for your Paint object and also use the Path class to draw your arc

I create an example for you, please test it:

import 'dart:math' as math;

import 'package:flutter/material.dart';

main() {
  runApp(MaterialApp(
    home: Home(),
  ));
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 300,
          height: 300,
          child: CustomPaint(
            painter: MakeCircle(strokeWidth: 50,strokeCap: StrokeCap.round),
          ),
        ),
      ),
    );
  }
}




class MakeCircle extends CustomPainter {
  final double strokeWidth;
  final StrokeCap strokeCap;

  MakeCircle({this.strokeCap = StrokeCap.square, this.strokeWidth = 10.0});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.round
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke; //important set stroke style

    final path = Path()
      ..moveTo(strokeWidth, strokeWidth)
      ..arcToPoint(Offset(size.width - strokeWidth, size.height - strokeWidth),
          radius: Radius.circular(math.max(size.width, size.height)));

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}



Upvotes: 4

Related Questions