gpt4 book ai didi

Flutter 使用 CustomPainter 绘制心形

转载 作者:行者123 更新时间:2023-12-03 02:43:47 28 4
gpt4 key购买 nike

我想知道是否有人对如何开始使用 CustomPainter 在 flutter 中绘制心形有任何指示。我已经设法画了三角形和正方形,或者一个基本的圆,但心当然有直线和曲线。

我有这个画一个三角形,看起来有点像心脏,但不知道如何获得心脏所需的曲线。

class Heart extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: CustomPaint(
painter: TrianglePainter(
strokeColor: Color(0xFFF27788),
paintingStyle: PaintingStyle.fill,
),
child: Container(
height: 60 * Dep.hr,
width: 60 * Dep.hr,
),
),
);
}
}

class TrianglePainter extends CustomPainter {
final Color strokeColor;
final PaintingStyle paintingStyle;
final double strokeWidth;

TrianglePainter({this.strokeColor, this.strokeWidth = 3, this.paintingStyle = PaintingStyle.stroke});

@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = strokeColor
..strokeWidth = strokeWidth
..style = paintingStyle;

canvas.drawPath(getTrianglePath(size.width, size.height), paint);
}

Path getTrianglePath(double x, double y) {
return Path()
..moveTo(y, 0)
..lineTo(0, 0)
..lineTo(x / 2, y);
}

@override
bool shouldRepaint(TrianglePainter oldDelegate) {
return oldDelegate.strokeColor != strokeColor ||
oldDelegate.paintingStyle != paintingStyle ||
oldDelegate.strokeWidth != strokeWidth;
}
}

它也只是一个颜色块,但我真的需要一个围绕形状的边框。这是我的预期输出,不确定是否是一厢情愿。

enter image description here

最佳答案

试试这个 :

  class HeartWidget extends StatefulWidget {
@override
_HeartWidgetState createState() => _HeartWidgetState();
}

class _HeartWidgetState extends State<HeartWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Testing'),
),
body: Center(
child: CustomPaint(
size: Size(70, 80),
painter: HeartPainter(),
),
),
);
}
}

class HeartPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// TODO: implement paint
Paint paint = Paint();
paint
..color = Colors.black
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = 6;

Paint paint1 = Paint();
paint1
..color = Colors.red
..style = PaintingStyle.fill
..strokeWidth = 0;

double width = size.width;
double height = size.height;

Path path = Path();
path.moveTo(0.5 * width, height * 0.35);
path.cubicTo(0.2 * width, height * 0.1, -0.25 * width, height * 0.6,
0.5 * width, height);
path.moveTo(0.5 * width, height * 0.35);
path.cubicTo(0.8 * width, height * 0.1, 1.25 * width, height * 0.6,
0.5 * width, height);

canvas.drawPath(path, paint1);
canvas.drawPath(path, paint);
}

@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}

enter image description here

关于Flutter 使用 CustomPainter 绘制心形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57756692/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com