Flutter drawArc() method draws full circle not just arc
How to draw arcs
To paint in Flutter you use the CustomPaint
widget. The CustomPaint
widget takes a CustomPainter
object as a parameter. In that class you have to override the paint
method, which gives you a canvas that you can paint on. Here is the code to draw the arc in the image above.
// Don't forget: import 'dart:math' as math;
@override
void paint(Canvas canvas, Size size) {
final rect = Rect.fromLTRB(50, 100, 250, 200);
final startAngle = -math.pi / 2;
final sweepAngle = math.pi;
final useCenter = false;
final paint = Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 4;
canvas.drawArc(rect, startAngle, sweepAngle, useCenter, paint);
}
Notes:
- The
rect
is what the full oval would be inscribed within. - The
startAngle
is the location on the oval that the line starts drawing from. An angle of 0 is at the right side. Angles are in radians, not degrees. The top is at 3π/2 (or -π/2), the left at π, and the bottom at π/2. - The
sweepAngle
is how much of the oval is included in the arc. Again, angles are in radians. A value of 2π would draw the entire oval. - If you set
useCenter
to true, then there will be a straight line from both sides of the arc to the center.
Context
Here is the main.dart code so that you can see it in context.
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: HomeWidget(),
),
);
}
}
class HomeWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: CustomPaint( // <-- CustomPaint widget
size: Size(300, 300),
painter: MyPainter(),
),
);
}
}
class MyPainter extends CustomPainter { // <-- CustomPainter class
@override
void paint(Canvas canvas, Size size) {
// <-- Insert your painting code here.
}
@override
bool shouldRepaint(CustomPainter old) {
return false;
}
}
See also
See this article for my fuller answer.
https://docs.flutter.io/flutter/dart-ui/Canvas/drawArc.html
It starts from startAngle radians around the oval up to startAngle + sweepAngle radians around the oval, with zero radians
It expects Radians instead of Degrees:
canvas.drawArc(new Rect.fromLTWH(0.0, 0.0, size.width/2, size.height/2),
0.175, 0.349, false, paint);