Flutter 绘制集录 | Shader 让绘制无限强大 - 壹
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Shader 示例')),
body: Center(
child: CustomPaint(
size: Size(200, 200),
painter: ShaderPainter(),
),
),
);
}
}
class ShaderPainter extends CustomPainter {
// 创建一个线性渐变
final LinearGradient gradient = LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.red, Colors.blue],
);
@override
void paint(Canvas canvas, Size size) {
// 创建一个矩形区域并应用渐变Shader
Rect rect = Offset.zero & size;
Paint paint = Paint()
..shader = gradient.createShader(rect);
// 绘制矩形
canvas.drawRect(rect, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false; // 自定义的绘制不依赖于配置或动画,所以返回false
}
}
这段代码创建了一个带有渐变效果的矩形,演示了如何在Flutter中使用Shader来实现复杂的绘制效果。通过创建一个LinearGradient对象,并使用它来创建一个Shader,然后在Canvas上绘制矩形。这个例子简单而直观,展示了如何将Shader集成到Flutter应用程序中。
评论已关闭