Skip to content

Instantly share code, notes, and snippets.

@knezzz
Last active March 19, 2019 07:28
Show Gist options
  • Select an option

  • Save knezzz/ac4b05072d1316ae662c55a503d640b8 to your computer and use it in GitHub Desktop.

Select an option

Save knezzz/ac4b05072d1316ae662c55a503d640b8 to your computer and use it in GitHub Desktop.
Gradient text in Flutter
class GradientText extends StatelessWidget {
const GradientText(this.text, {
Key key,
@required this.gradient,
this.style = const TextStyle(),
}) : super(key: key);
final String text;
final TextStyle style;
final Gradient gradient;
@override
Widget build(BuildContext context) {
// Get exact size of the text view
final TextPainter _painter = TextPainter(text: TextSpan(text: text, style: style), textDirection: TextDirection.rtl);
// Call layout method so width and height of this text widget get measured
_painter.layout();
return CustomPaint(
size: _painter.size,
painter: _GradientTextPainter(
text: text,
style: style,
gradient: gradient
),
);
}
}
class _GradientTextPainter extends CustomPainter {
final Gradient gradient;
final String text;
final TextStyle style;
_GradientTextPainter({
Listenable repaint,
@required this.text,
@required this.style,
@required this.gradient
}) : super(repaint: repaint);
@override
void paint(Canvas canvas, Size size) {
final Paint _gradientShaderPaint = new Paint()..shader = gradient.createShader(
new Rect.fromLTWH(0.0, 0.0, size.width, size.height)
);
final ui.ParagraphBuilder _builder = new ui.ParagraphBuilder(ui.ParagraphStyle())
..pushStyle(new ui.TextStyle(
foreground: _gradientShaderPaint,
fontSize: style.fontSize,
fontWeight: style.fontWeight,
height: style.height,
decoration: style.decoration,
decorationColor: style.decorationColor,
decorationStyle: style.decorationStyle,
fontStyle: style.fontStyle,
letterSpacing: style.letterSpacing,
fontFamily: style.fontFamily,
locale: style.locale,
textBaseline: style.textBaseline,
wordSpacing: style.wordSpacing,
))
..addText(text);
final ui.Paragraph _paragraph = _builder.build();
_paragraph.layout(new ui.ParagraphConstraints(width: size.width));
canvas.drawParagraph(_paragraph, Offset.zero);
}
@override
bool shouldRepaint(_GradientTextPainter oldDelegate) {
return gradient != oldDelegate.gradient ||
text != oldDelegate.text ||
style != oldDelegate.style;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment