【自学Flutter】34 自定义Widget(自绘)
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('自定义Widget示例'),
),
body: Center(
child: MyCustomWidget(),
),
),
);
}
}
class MyCustomWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: MyPainter(),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..strokeWidth = 5.0
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke;
canvas.drawLine(Offset(0.0, size.height / 2), Offset(size.width, size.height / 2), paint);
canvas.drawLine(Offset(size.width / 2, 0.0), Offset(size.width / 2, size.height), paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
这段代码定义了一个自定义的Widget,它使用CustomPaint组件来渲染一个由两条蓝色直线组成的十字形标记。MyPainter类继承自CustomPainter,并实现了绘制逻辑。shouldRepaint方法返回false表示当组件重绘时不需要重新调用paint方法。这是一个简单的自绘示例,展示了如何在Flutter中创建和使用自定义的绘图组件。
评论已关闭