flutter - 如何在 Flutter 中绘制自定义背景?
问题描述
我需要画出上面的背景。我无法绘制黑色和蓝色背景。
class _BackGroundPainter extends CustomPainter{
@override
void paint(Canvas canvas, Size size) {
Path path = Path();
Paint paint = Paint();
path.moveTo(0, size.height*0.2);
path.quadraticBezierTo(size.width * 0.135, size.height * 0.178, size.width * 0.281, size.height*0.0889);
path.quadraticBezierTo(size.width * 0.4, size.height * 0.0113, size.width*0.8, 0);
path.lineTo(0, 0);
path.lineTo(0, size.width*0.8);
path.close();
paint.color = Colors.yellowAccent;
canvas.drawPath(path, paint);
path = Path();
path.moveTo(0, size.height * 0.4);
path.quadraticBezierTo(size.width*0.4, size.height * 0.5, size.width*0.6, size.height*0.25);
path.quadraticBezierTo(size.width*0.7, size.height*0.15, size.width, size.height*0.1);
path.lineTo(0, 0);
paint.color = Colors.black87;
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
这是我的代码,我只能画黄线
解决方案
为此,您可以将CustomPainter与Canvas类一起使用。正如@Farhana 建议的那样,您可以使用图像,但该方法有一些缺点
内存昂贵
不可扩展
...
这是从官方文档中绘制天空背景的示例
class Sky extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var rect = Offset.zero & size;
var gradient = RadialGradient(
center: const Alignment(0.7, -0.6),
radius: 0.2,
colors: [const Color(0xFFFFFF00), const Color(0xFF0099FF)],
stops: [0.4, 1.0],
);
canvas.drawRect(
rect,
Paint()..shader = gradient.createShader(rect),
);
}
@override
SemanticsBuilderCallback get semanticsBuilder {
return (Size size) {
var rect = Offset.zero & size;
var width = size.shortestSide * 0.4;
rect = const Alignment(0.8, -0.9).inscribe(Size(width, width), rect);
return [
CustomPainterSemantics(
rect: rect,
properties: SemanticsProperties(
label: 'Sun',
textDirection: TextDirection.ltr,
),
),
];
};
}
@override
bool shouldRepaint(Sky oldDelegate) => false;
@override
bool shouldRebuildSemantics(Sky oldDelegate) => false;
}
推荐阅读
- sql - 如何将多个 SQL 列合并为一列?
- sql - 基于日期的 Oracle SQL 最近行
- kdb - 使用over副词对桌子进行操作
- javascript - 打字稿尝试更新我的对象中的布尔属性收到“TypeError:无法分配给只读属性”
- ios - 点击时如何调整 UIImageView 的大小?
- asp.net-mvc - asp.net mvc中的Excel导出和导入
- microsoft-teams - Microsoft Teams 连接器配置保存失败
- angular - ngdart 生成组件不生成 css 文件?
- node.js - 为什么闪存错误并非一直有效?
- mongodb - 如何将数据库移动到mongodb中的另一个分片