Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Created June 21, 2024 03:04
Show Gist options
  • Save jonahwilliams/7e8a0b5d13b347b85076d822a271cbe1 to your computer and use it in GitHub Desktop.
Save jonahwilliams/7e8a0b5d13b347b85076d822a271cbe1 to your computer and use it in GitHub Desktop.
Linear gradient with non-linear easing
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CustomPaint(
painter: FooPainter(Curves.linear),
size: Size(200, 200),
),
SizedBox(width: 16),
CustomPaint(
painter: FooPainter(Curves.easeIn),
size: Size(200, 200),
),
],
),
),
);
}
}
class FooPainter extends CustomPainter {
FooPainter(this.curve);
final Curve curve;
void paint(Canvas canvas, Size size) {
var paint = Paint();
paint.shader = ui.Gradient.linear(
Offset(size.width / 2, 0),
Offset(size.width / 2, size.height),
[Colors.yellow, Colors.blue],
[0, 1],
);
var startColor = Colors.yellow;
var endColor = Colors.blue;
var colors = <Color>[];
var stops = <double>[];
for (var i = 0; i < 32; i++) {
var value = (i / 32.0).clamp(0.0, 1.0);
var transformed = curve.transform(value);
colors.add(Color.lerp(startColor, endColor, transformed)!);
stops.add(value);
}
paint.shader = ui.Gradient.linear(
Offset(size.width / 2, 0),
Offset(size.width / 2, size.height),
colors,
stops,
);
canvas.drawRRect(
RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(8)), paint);
}
bool shouldRepaint(covariant FooPainter painter) {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment