Skip to content

Instantly share code, notes, and snippets.

@rhalff
Last active August 18, 2019 21:30
Show Gist options
  • Select an option

  • Save rhalff/08323615dceacc6af1df72baae3cdd73 to your computer and use it in GitHub Desktop.

Select an option

Save rhalff/08323615dceacc6af1df72baae3cdd73 to your computer and use it in GitHub Desktop.
Custom Star Painter
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
const double _kRadiansPerDegree = math.pi / 180;
class Star extends StatelessWidget {
final Color color;
final double ratio;
final double startAngle;
final int spikes;
const Star({
Key key,
this.color = Colors.yellow,
this.ratio = 0.5,
this.spikes = 21,
this.startAngle = -90.0,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return CustomPaint(
size: size,
painter: StarPainter(
color: color,
ratio: ratio,
startAngle: startAngle,
spikes: spikes,
),
);
}
}
class StarPainter extends CustomPainter {
StarPainter({
this.color,
this.startAngle,
this.ratio = 0.5,
this.spikes = 10,
}) : super();
final Color color;
final double startAngle;
final double ratio;
final int spikes;
Path _buildStarPath(
double radius,
double innerRadius,
) {
final Offset center = Offset(radius, radius);
final Path path = Path();
var distance = innerRadius;
path.moveTo(center.dx, center.dy);
double step = 360 / (spikes * 2);
var stopAngle = 360 + startAngle;
double x;
double y;
double angle;
for (angle = startAngle; angle <= stopAngle; angle = angle + step) {
distance = distance == radius ? innerRadius : radius;
x = distance * math.cos(angle * _kRadiansPerDegree);
y = distance * math.sin(angle * _kRadiansPerDegree);
path.lineTo(center.dx + x, center.dy + y);
}
if (angle != stopAngle) {
distance = distance == radius ? innerRadius : radius;
x = distance * math.cos(startAngle * _kRadiansPerDegree);
y = distance * math.sin(startAngle * _kRadiansPerDegree);
path.lineTo(center.dx + x, center.dy + y);
}
path.close();
return path;
}
@override
void paint(Canvas canvas, Size size) {
final double radius = size.width / 2;
final double innerRadius = radius * (1 - ratio);
final path = _buildStarPath(radius, innerRadius);
final Paint slicePaint = Paint()
..style = PaintingStyle.fill
..isAntiAlias = true
..color = color;
canvas.drawPath(path, slicePaint);
}
@override
bool shouldRepaint(StarPainter oldDelegate) => false;
}
@rhalff

rhalff commented Aug 18, 2019

Copy link
Copy Markdown
Author

Usage:

Star(
  spikes: 21,
  ratio: 0.5,
  color: Colors.yellow,
);

Star(
  spikes: 100,
  ratio: 0.5,
  color: Colors.yellow,
);

Star(
  spikes: 300,
  ratio: 0.5,
  color: Colors.yellow,
);

Star(
   spikes: 5,
   ratio: 0.6,
   color: Colors.white,
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment