I am trying to draw a circle with 12 segments and with Random colors in Flutter. I am using CustomPainter with drawArc method.
I am check for the screen size first to ensure that the app is responsive in all phones. To this, I am get the screenheight and screenwidth as follows:
if (screenheight - safearea > screenwidth / 2) {
blockwidth = screenheight - safearea;
blockheight = screenheight - safearea;
setState(() {});
} else {
blockwidth = screenwidth / 2;
blockheight = screenheight - safearea;
setState(() {});
}
Once I have the block sizes, I am calling the InnerRing passing the height and width from homepage. This is the InnerRing.
import 'dart:math';
import 'package:flutter/material.dart';
class InnerRing extends StatelessWidget {
final double width;
final double height;
const InnerRing({Key? key, required this.width, required this.height})
: super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: CustomPaint(
painter: MaasaRing(width: width, height: height),
),
);
}
}
class MaasaRing extends CustomPainter {
final double width;
final double height;
MaasaRing({required this.width, required this.height});
@override
void paint(Canvas canvas, Size size) {
double offwidth = width / 4;
double offheight = height / 4;
double sizewidth = width / 2;
double sizeheight = height / 2;
Paint arc(int color) {
final paint = Paint()
..color =
Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0)
..style = PaintingStyle.stroke
..strokeWidth = 18;
return paint;
}
double stepup = 0;
for (int i = 0; i < 12; i++) {
canvas.drawArc(Offset(offwidth, offheight) & Size(sizewidth, sizeheight),
stepup, 1 * pi / 6, false, arc(i));
stepup = stepup + .5;
print(stepup);
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}
Question is why am I getting this gap in the circle. I am expecting to see 12 arcs complete the 360°. Check the image enclosed.
2
Answers
The problem is that you increment
stepup
by0.5
on every iteration. That will result in12 * 0.5
=6.0
for the entire loop, but it should by2 * pi
to fill the entire circle. The difference is what you see as an empty arc.Change this:
to this:
Adding to Peter’s answer, there is one more point that could cause part of the circle becoming black. The way you initialize the color
might cause it to be entirely black, because
nextDouble()
can return 0.