{"id":417756,"date":"2024-06-30T01:44:43","date_gmt":"2024-06-30T01:44:43","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=417756"},"modified":"-0001-11-30T00:00:00","modified_gmt":"2024-06-30T01:44:43","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=417756","title":{"rendered":"<span>How to Create a Half Circle Progress Bar<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<figure class=\"\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/b40\/090\/219\/b40090219ea1e45c8258eff1550f4f59.gif\" width=\"400\" height=\"263\" data-src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/b40\/090\/219\/b40090219ea1e45c8258eff1550f4f59.gif\"\/><figcaption><\/figcaption><\/figure>\n<p>I bet you all had situations when a designer made a cool-looking UI and you just thought \u201ccool, but how to implement this\u201d. The same happened to me when a saw this progress bar in Figma.<\/p>\n<p>Good thing is that in Flutter it\u2019s pretty easy to create custom views and they will look awesome on every platform, but sometimes you just need to remember all these things that you have learned in geometric, and math classes. <em><sup><sub>Yeah, we don\u2019t always change the button\u2019s color as someone thinks \ud83d\ude42<\/sub><\/sup><\/em><\/p>\n<hr\/>\n<h2>A little bit of geometry<\/h2>\n<p>Let\u2019s think what we have to make to implement the progress bar. Firstly, we have to find out a way to understand how many dots should be on the half-circle. Secondly, how to place these dots on it.<\/p>\n<h3>Calculating the number of dots<\/h3>\n<p>Let\u2019s  start simple, what if we have a straight line and we need to calculate  how many points it can fit. The answer is that you take the length of  the line, divide it by the diameter of the dot and add padding between them. And that\u2019s done.<\/p>\n<p>We do the same, but with a circle. If you know the radius of the circle, we can find its length. The formula is <code>2 * pi * r<\/code>, but we need only half of it, so for us, the formula will be:<\/p>\n<pre><code>lineLength = pi * r<\/code><\/pre>\n<p>Finally, we know the size (radius or diameter) of the dots and the spacing between them, so we can simply divide the line\u2019s length by the size of the dots with spacing. The formula will be:<\/p>\n<pre><code>dotsNumber = floor(lineLength \/ (dotDiameter + dotsSpacing))<\/code><\/pre>\n<p>We use floor because we can\u2019t draw, say, half of the dot.<\/p>\n<h3>Placing dots on the circle<\/h3>\n<p>If we had a line, that would be easy to place the dots on it. We will start from 0 and add <code>dotDiameter + dotsSpacing<\/code> after the dots have been drawn.<\/p>\n<p>Unfortunately,  in our case, we can\u2019t do it like that. To place dots on the circle we  will use Polar Coordinates and will specify two coordinates:<\/p>\n<ol>\n<li>\n<p>how far away is the dot from the circle\u2019s center <strong>(r)<\/strong>,<\/p>\n<\/li>\n<li>\n<p>dot\u2019s angle <strong><em>(\u03b8)<\/em><\/strong>.<\/p>\n<\/li>\n<\/ol>\n<p>Having these coordinated we can easily convert them to Cartesian coordinates and draw afterward. The formulas are:<\/p>\n<pre><code>x = circleRadius * sin(dotAngle) + circleCenterX y = circleRadius * cos(dotAngle) + circleCenterY<\/code><\/pre>\n<h2>Implementation<\/h2>\n<p>We have everything to start implementing the progress bar. We will use a <code>CustomPainter<\/code> class to draw the view on the canvas.<\/p>\n<h3>The painters<\/h3>\n<p>Let\u2019s add all arguments that we need and implement methods the <code>CustomPainter<\/code> requires, but the <code>paint<\/code> method.<\/p>\n<pre><code class=\"dart\">class _DiagramPainter extends CustomPainter {   _DiagramPainter({     required this.dotRadius,     required this.startBarRadius,     required this.layers,     required this.layersSpacing,     required this.dotsSpacing,     required this.progress,     required Color dotColor,     required Color progressDotColor,   })  : _paint = Paint()           ..color = dotColor           ..style = PaintingStyle.fill,         _progressPaint = Paint()           ..color = progressDotColor           ..style = PaintingStyle.fill,         _dotDiameter = dotRadius * 2,         _dotsSizeWithSpacing = dotRadius * 2 + dotsSpacing;    final double dotRadius;   final double startBarRadius;   final int layers;   final double layersSpacing;   final double dotsSpacing;   final double progress;    final Paint _paint;   final Paint _progressPaint;    final double _dotDiameter;   final double _dotsSizeWithSpacing;    static const _startAngle = 270.0;   static const _circle = 360.0;   static const _halfCircle = 180.0;    @override   void paint(Canvas canvas, Size size) {     \/\/ implement this later   }    @override   bool shouldRepaint(covariant _DiagramPainter oldDelegate) =>       dotRadius != oldDelegate.dotRadius ||       startBarRadius != oldDelegate.startBarRadius ||       layers != oldDelegate.layers ||       layersSpacing != oldDelegate.layersSpacing ||       dotsSpacing != oldDelegate.dotsSpacing ||       progress != oldDelegate.progress; }<\/code><\/pre>\n<p>There  we have arguments to customize the progress bar, like the dot\u2019s colors, spacing between dots and layers, and radius of the first (inner) circle. Also, we create the painters, so we won\u2019t instantiate them every time in the painting method.<\/p>\n<p>Don\u2019t forget to implement <code>shouldRepaint<\/code> method, so the view gets repainted once one of the arguments is changed.<\/p>\n<h3>Draw first layer of circles<\/h3>\n<p>Let\u2019s implement the <code>paint<\/code> method that draws a circle with dots.<\/p>\n<pre><code class=\"dart\">@override void paint(Canvas canvas, Size size) {   final center = size.bottomCenter(Offset(0, -dotRadius));    final lengthOfHalfCircle = pi * startBarRadius;    final dotsNumber = (lengthOfHalfCircle \/ _dotsSizeWithSpacing).floor();    final angleStep = _halfCircle \/ (dotsNumber - 1);   var angle = _startAngle;    final progressItems = (dotsNumber * progress).toInt();    for (var dot = 0; dot &lt; dotsNumber; dot++) {     final radian = pi * 2 * angle \/ _circle;      canvas.drawCircle(       Offset(         radius * sin(radian) + center.dx,         radius * cos(radian) + center.dy,       ),       dotRadius,       dot &lt; progressItems ? _progressPaint : _paint,     );      angle -= angleStep;   } }<\/code><\/pre>\n<p>Here we get the center of the circle, calculating how many dots will be on the circle and the angle between them.<\/p>\n<p>The important thing here is that we start drawing the dots from 270 angles (<code>_startAngle<\/code>) because we want the first dot to be in the bottom left corner and moving clockwise.<\/p>\n<p>Also, have a look at how we calculate how many dots should have different (progress) colors.<\/p>\n<h3>Draw more layers<\/h3>\n<p>The last thing is to add more layers.<\/p>\n<pre><code class=\"dart\">@override void paint(Canvas canvas, Size size) {   final center = size.bottomCenter(Offset(0, -dotRadius));    var radius = startBarRadius;    for (var layer = 0; layer &lt; layers; layer++) {     final lengthOfHalfCircle = pi * radius;      final dotsNumber = (lengthOfHalfCircle \/ _dotsSizeWithSpacing).floor();      final angleStep = _halfCircle \/ (dotsNumber - 1);     var angle = _startAngle;      final progressItems = (dotsNumber * progress).toInt();      for (var dot = 0; dot &lt; dotsNumber; dot++) {       final radian = pi * 2 * angle \/ _circle;        canvas.drawCircle(         Offset(           radius * sin(radian) + center.dx,           radius * cos(radian) + center.dy,         ),         dotRadius,         dot &lt; progressItems ? _progressPaint : _paint,       );        angle -= angleStep;     }      radius += _dotDiameter + layersSpacing;   } }<\/code><\/pre>\n<p>A for-loop has been added and for every tick, we just increase the circle\u2019s radius by adding the dot\u2019s diameter and spacing between layers.<\/p>\n<h3>Wrap it<\/h3>\n<p>You can use your <code>CustomPainter<\/code> by wrapping it with the <code>CustomPaint<\/code> widget, but I think that is not user-friendly. So let\u2019s wrap the painter with our widget.<\/p>\n<pre><code class=\"dart\">class HalfCircleProgressBar extends StatelessWidget {   const HalfCircleProgressBar({     Key? key,     required this.progress,     required this.dotColor,     required this.progressDotColor,     this.dotRadius = _defaultDotRadius,     this.startBarRadius = _defaultStartBarRadius,     this.layers = _defaultLayers,     this.layersSpacing = _defaultLayersSpacing,     this.dotsSpacing = _defaultDotsSpacing,   }) : super(key: key);    final double progress;   final double dotRadius;   final double startBarRadius;   final int layers;   final double layersSpacing;   final double dotsSpacing;   final Color dotColor;   final Color progressDotColor;    static const _defaultDotRadius = 4.0;   static const _defaultStartBarRadius = 68.0;   static const _defaultLayers = 10;   static const _defaultLayersSpacing = 1.0;   static const _defaultDotsSpacing = 1.0;    @override   Widget build(BuildContext context) {     final height = startBarRadius + (layersSpacing + dotRadius * 2) * layers;     return ClipRect(       child: CustomPaint(         size: Size(height * 2, height),         painter: _DiagramPainter(           dotRadius: dotRadius,           startBarRadius: startBarRadius,           layers: layers,           layersSpacing: layersSpacing,           dotsSpacing: dotsSpacing,           progress: progress,           dotColor: dotColor,           progressDotColor: progressDotColor,         ),       ),     );   } }<\/code><\/pre>\n<p>Here  is the widget that encapsulates some things about the painter and adds  default values for the required arguments. The important thing here is  that we add size for the <code>CustomPaint<\/code> so that <code>Painter<\/code> knows the size of the canvas and the widget can be correctly positioned, for example, in a <code>Stack<\/code> widget.<\/p>\n<p>Also, <code>ClipRect<\/code>  is added to cut everything that is out of the parent widget. That happens when a parent widget is smaller than the size needed to draw the  progress bar.<\/p>\n<p>Here is the link to the repository \u2014 <a href=\"https:\/\/github.com\/ValeryPonomarenko\/flutter-half-circle-progress-bar\" rel=\"noopener noreferrer nofollow\">https:\/\/github.com\/ValeryPonomarenko\/flutter-half-circle-progress-bar<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/694088\/\"> https:\/\/habr.com\/ru\/articles\/694088\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<figure class=\"\"><figcaption><\/figcaption><\/figure>\n<p>I bet you all had situations when a designer made a cool-looking UI and you just thought \u201ccool, but how to implement this\u201d. The same happened to me when a saw this progress bar in Figma.<\/p>\n<p>Good thing is that in Flutter it\u2019s pretty easy to create custom views and they will look awesome on every platform, but sometimes you just need to remember all these things that you have learned in geometric, and math classes. <em><sup><sub>Yeah, we don\u2019t always change the button\u2019s color as someone thinks \ud83d\ude42<\/sub><\/sup><\/em><\/p>\n<hr\/>\n<h2>A little bit of geometry<\/h2>\n<p>Let\u2019s think what we have to make to implement the progress bar. Firstly, we have to find out a way to understand how many dots should be on the half-circle. Secondly, how to place these dots on it.<\/p>\n<h3>Calculating the number of dots<\/h3>\n<p>Let\u2019s  start simple, what if we have a straight line and we need to calculate  how many points it can fit. The answer is that you take the length of  the line, divide it by the diameter of the dot and add padding between them. And that\u2019s done.<\/p>\n<p>We do the same, but with a circle. If you know the radius of the circle, we can find its length. The formula is <code>2 * pi * r<\/code>, but we need only half of it, so for us, the formula will be:<\/p>\n<pre><code>lineLength = pi * r<\/code><\/pre>\n<p>Finally, we know the size (radius or diameter) of the dots and the spacing between them, so we can simply divide the line\u2019s length by the size of the dots with spacing. The formula will be:<\/p>\n<pre><code>dotsNumber = floor(lineLength \/ (dotDiameter + dotsSpacing))<\/code><\/pre>\n<p>We use floor because we can\u2019t draw, say, half of the dot.<\/p>\n<h3>Placing dots on the circle<\/h3>\n<p>If we had a line, that would be easy to place the dots on it. We will start from 0 and add <code>dotDiameter + dotsSpacing<\/code> after the dots have been drawn.<\/p>\n<p>Unfortunately,  in our case, we can\u2019t do it like that. To place dots on the circle we  will use Polar Coordinates and will specify two coordinates:<\/p>\n<ol>\n<li>\n<p>how far away is the dot from the circle\u2019s center <strong>(r)<\/strong>,<\/p>\n<\/li>\n<li>\n<p>dot\u2019s angle <strong><em>(\u03b8)<\/em><\/strong>.<\/p>\n<\/li>\n<\/ol>\n<p>Having these coordinated we can easily convert them to Cartesian coordinates and draw afterward. The formulas are:<\/p>\n<pre><code>x = circleRadius * sin(dotAngle) + circleCenterX y = circleRadius * cos(dotAngle) + circleCenterY<\/code><\/pre>\n<h2>Implementation<\/h2>\n<p>We have everything to start implementing the progress bar. We will use a <code>CustomPainter<\/code> class to draw the view on the canvas.<\/p>\n<h3>The painters<\/h3>\n<p>Let\u2019s add all arguments that we need and implement methods the <code>CustomPainter<\/code> requires, but the <code>paint<\/code> method.<\/p>\n<pre><code class=\"dart\">class _DiagramPainter extends CustomPainter {   _DiagramPainter({     required this.dotRadius,     required this.startBarRadius,     required this.layers,     required this.layersSpacing,     required this.dotsSpacing,     required this.progress,     required Color dotColor,     required Color progressDotColor,   })  : _paint = Paint()           ..color = dotColor           ..style = PaintingStyle.fill,         _progressPaint = Paint()           ..color = progressDotColor           ..style = PaintingStyle.fill,         _dotDiameter = dotRadius * 2,         _dotsSizeWithSpacing = dotRadius * 2 + dotsSpacing;    final double dotRadius;   final double startBarRadius;   final int layers;   final double layersSpacing;   final double dotsSpacing;   final double progress;    final Paint _paint;   final Paint _progressPaint;    final double _dotDiameter;   final double _dotsSizeWithSpacing;    static const _startAngle = 270.0;   static const _circle = 360.0;   static const _halfCircle = 180.0;    @override   void paint(Canvas canvas, Size size) {     \/\/ implement this later   }    @override   bool shouldRepaint(covariant _DiagramPainter oldDelegate) =>       dotRadius != oldDelegate.dotRadius ||       startBarRadius != oldDelegate.startBarRadius ||       layers != oldDelegate.layers ||       layersSpacing != oldDelegate.layersSpacing ||       dotsSpacing != oldDelegate.dotsSpacing ||       progress != oldDelegate.progress; }<\/code><\/pre>\n<p>There  we have arguments to customize the progress bar, like the dot\u2019s colors, spacing between dots and layers, and radius of the first (inner) circle. Also, we create the painters, so we won\u2019t instantiate them every time in the painting method.<\/p>\n<p>Don\u2019t forget to implement <code>shouldRepaint<\/code> method, so the view gets repainted once one of the arguments is changed.<\/p>\n<h3>Draw first layer of circles<\/h3>\n<p>Let\u2019s implement the <code>paint<\/code> method that draws a circle with dots.<\/p>\n<pre><code class=\"dart\">@override void paint(Canvas canvas, Size size) {   final center = size.bottomCenter(Offset(0, -dotRadius));    final lengthOfHalfCircle = pi * startBarRadius;    final dotsNumber = (lengthOfHalfCircle \/ _dotsSizeWithSpacing).floor();    final angleStep = _halfCircle \/ (dotsNumber - 1);   var angle = _startAngle;    final progressItems = (dotsNumber * progress).toInt();    for (var dot = 0; dot &lt; dotsNumber; dot++) {     final radian = pi * 2 * angle \/ _circle;      canvas.drawCircle(       Offset(         radius * sin(radian) + center.dx,         radius * cos(radian) + center.dy,       ),       dotRadius,       dot &lt; progressItems ? _progressPaint : _paint,     );      angle -= angleStep;   } }<\/code><\/pre>\n<p>Here we get the center of the circle, calculating how many dots will be on the circle and the angle between them.<\/p>\n<p>The important thing here is that we start drawing the dots from 270 angles (<code>_startAngle<\/code>) because we want the first dot to be in the bottom left corner and moving clockwise.<\/p>\n<p>Also, have a look at how we calculate how many dots should have different (progress) colors.<\/p>\n<h3>Draw more layers<\/h3>\n<p>The last thing is to add more layers.<\/p>\n<pre><code class=\"dart\">@override void paint(Canvas canvas, Size size) {   final center = size.bottomCenter(Offset(0, -dotRadius));    var radius = startBarRadius;    for (var layer = 0; layer &lt; layers; layer++) {     final lengthOfHalfCircle = pi * radius;      final dotsNumber = (lengthOfHalfCircle \/ _dotsSizeWithSpacing).floor();      final angleStep = _halfCircle \/ (dotsNumber - 1);     var angle = _startAngle;      final progressItems = (dotsNumber * progress).toInt();      for (var dot = 0; dot &lt; dotsNumber; dot++) {       final radian = pi * 2 * angle \/ _circle;        canvas.drawCircle(         Offset(           radius * sin(radian) + center.dx,           radius * cos(radian) + center.dy,         ),         dotRadius,         dot &lt; progressItems ? _progressPaint : _paint,       );        angle -= angleStep;     }      radius += _dotDiameter + layersSpacing;   } }<\/code><\/pre>\n<p>A for-loop has been added and for every tick, we just increase the circle\u2019s radius by adding the dot\u2019s diameter and spacing between layers.<\/p>\n<h3>Wrap it<\/h3>\n<p>You can use your <code>CustomPainter<\/code> by wrapping it with the <code>CustomPaint<\/code> widget, but I think that is not user-friendly. So let\u2019s wrap the painter with our widget.<\/p>\n<pre><code class=\"dart\">class HalfCircleProgressBar extends StatelessWidget {   const HalfCircleProgressBar({     Key? key,     required this.progress,     required this.dotColor,     required this.progressDotColor,     this.dotRadius = _defaultDotRadius,     this.startBarRadius = _defaultStartBarRadius,     this.layers = _defaultLayers,     this.layersSpacing = _defaultLayersSpacing,     this.dotsSpacing = _defaultDotsSpacing,   }) : super(key: key);    final double progress;   final double dotRadius;   final double startBarRadius;   final int layers;   final double layersSpacing;   final double dotsSpacing;   final Color dotColor;   final Color progressDotColor;    static const _defaultDotRadius = 4.0;   static const _defaultStartBarRadius = 68.0;   static const _defaultLayers = 10;   static const _defaultLayersSpacing = 1.0;   static const _defaultDotsSpacing = 1.0;    @override   Widget build(BuildContext context) {     final height = startBarRadius + (layersSpacing + dotRadius * 2) * layers;     return ClipRect(       child: CustomPaint(         size: Size(height * 2, height),         painter: _DiagramPainter(           dotRadius: dotRadius,           startBarRadius: startBarRadius,           layers: layers,           layersSpacing: layersSpacing,           dotsSpacing: dotsSpacing,           progress: progress,           dotColor: dotColor,           progressDotColor: progressDotColor,         ),       ),     );   } }<\/code><\/pre>\n<p>Here  is the widget that encapsulates some things about the painter and adds  default values for the required arguments. The important thing here is  that we add size for the <code>CustomPaint<\/code> so that <code>Painter<\/code> knows the size of the canvas and the widget can be correctly positioned, for example, in a <code>Stack<\/code> widget.<\/p>\n<p>Also, <code>ClipRect<\/code>  is added to cut everything that is out of the parent widget. That happens when a parent widget is smaller than the size needed to draw the  progress bar.<\/p>\n<p>Here is the link to the repository \u2014 <a href=\"https:\/\/github.com\/ValeryPonomarenko\/flutter-half-circle-progress-bar\" rel=\"noopener noreferrer nofollow\">https:\/\/github.com\/ValeryPonomarenko\/flutter-half-circle-progress-bar<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/694088\/\"> https:\/\/habr.com\/ru\/articles\/694088\/<\/a><br \/><\/br><\/br><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-417756","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/417756","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=417756"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/417756\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=417756"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=417756"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=417756"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}