Skip to content

Instantly share code, notes, and snippets.

@untillnesss
Created July 14, 2024 14:46
Show Gist options
  • Save untillnesss/a2623e0edb516cd7fb63fa4e2c2d35bc to your computer and use it in GitHub Desktop.
Save untillnesss/a2623e0edb516cd7fb63fa4e2c2d35bc to your computer and use it in GitHub Desktop.
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
List<Offset> getBresenhamCirclePoints(
Offset center,
double radius,
) {
List<Offset> points = [];
int x = 0;
int y = radius.toInt();
int d = 3 - 2 * radius.toInt();
points.add(center);
while (x <= y) {
// 0
points.add(Offset(center.dx + x, center.dy - y));
// 90
points.add(Offset(center.dx + y, center.dy + x));
// 180
points.add(Offset(center.dx + x, center.dy + y));
// 270
points.add(Offset(center.dx - y, center.dy + x));
// Another angel
points.add(Offset(center.dx - x, center.dy - y));
points.add(Offset(center.dx - x, center.dy + y));
points.add(Offset(center.dx + y, center.dy - x));
points.add(Offset(center.dx - y, center.dy - x));
if (d > 0) {
y -= 1;
d = d - 4 * y;
} else {
x += 1;
d = d + 4 * x + 6;
}
}
return points;
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Bresenham Circle'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Container(
decoration: const BoxDecoration(
color: Colors.black,
),
width: 200,
height: 200,
child: CustomPaint(
size: const Size(200, 200),
painter: BresenhamCircle(),
),
),
),
);
}
}
class BresenhamCircle extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.red
..strokeWidth = 5;
Offset center = const Offset(100, 100);
List<Offset> points = getBresenhamCirclePoints(center, 100);
canvas.drawPoints(
PointMode.points,
points,
paint,
);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment