我对 flutter 完全陌生,我有一个问题,如果需要,如何在 UI 中包含曲线,如下图所示。
我已经使用 ClipOval 小部件进行了一些尝试(未完成),该小部件包装在 Stack 小部件内的 Positioned 小部件内。谁能告诉我这是正确的方法还是其他更好的方法?
这是我迄今为止尝试过的。
import 'package:flutter/material.dart';
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
final backgroundColor = const Color(0xFFAFEDB3);
final ellipse1 = const Color(0xB2F1FFEC);
final ellipse2 = const Color(0xff9FE3A4);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Login screen'),
),
body: Container(
// color: const Color.fromARGB(255, 154, 236, 156),
decoration: BoxDecoration(
color: backgroundColor
,
),
child: Stack(
children: [
Positioned(
top: -90,
left: -75,
height: 320,
width: 450,
child: ClipOval(
child: Container(
width: double.maxFinite,
height: 200,
color: ellipse1,
child: const Text(
'Green',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
),
Positioned(
top: -10,
right: -25,
height: 200,
width: 200,
child: ClipOval(
child: Container(
width: double.maxFinite,
height: 200,
color: ellipse2,
child: const Text(
'Green',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
),
],
),
),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Stack(
children: [
Container(
height: 200,
color: Colors.blue,
),
Positioned(
top: 0,
left: 0,
right: 0,
child: CustomPaint(
size: Size(MediaQuery.of(context).size.width, 200),
painter: CurvePainter(color: Colors.green),
),
),
Positioned(
top: 0,
left: 0,
right: 0,
child: CustomPaint(
size: Size(MediaQuery.of(context).size.width, 200),
painter: CurvePainter(color: Colors.orange),
),
),
],
),
),
);
}
}
class CurvePainter extends CustomPainter {
final Color color;
CurvePainter({required this.color});
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = color
..style = PaintingStyle.fill;
Path path = Path();
path.moveTo(0, size.height * 0.5);
path.quadraticBezierTo(
size.width * 0.25, size.height * 0.25, size.width * 0.5, size.height * 0.5);
path.quadraticBezierTo(
size.width * 0.75, size.height * 0.75, size.width, size.height * 0.5);
path.lineTo(size.width, size.height);
path.lineTo(0, size.height);
path.close();
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
在此代码中,我使用了
Stack
小部件在屏幕顶部将两个弯曲形状叠加在一起。 Positioned
小部件用于将弯曲形状放置在屏幕顶部。您可以根据您的设计需求调整曲线的颜色和形状。