gpt4 book ai didi

android - 点击按钮时如何在容器上画线

转载 作者:IT王子 更新时间:2023-10-29 07:20:28 25 4
gpt4 key购买 nike

我还在学习 Flutter,对 CustomPainter 还不是很了解。

以下代码不会在嵌套在 Column 中的 Container 上画线。我想在点击画线按钮时画线。

在调试代码时,我可以看到调用了 CustomPainter,但未绘制线条。

import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Home(),
),
);
}
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}
class _HomeState extends State<Home> {
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Draw Line'),
),
backgroundColor: Colors.white,
body: Column(
children: <Widget>[
SizedBox(
height: 200,
width: 200,
child: Container(),
),
RaisedButton(
onPressed: () {
CustomPaint(
painter: LinePainter(),
);
},
child: Text('Draw Line'),
)
],
),
);
}
}
class LinePainter extends CustomPainter {
Paint _paint;
LinePainter() {
_paint = Paint()
..color = Colors.amber
..strokeWidth = 8.0;
}
@override
void paint(Canvas canvas, Size size) {
canvas.drawLine(Offset(0.0, 0.0), Offset(size.width, size.height), _paint);
}
@override
bool shouldRepaint(LinePainter oldDelegate) {
return true;
}
}

最佳答案

您的小部件层次结构顺序错误。您需要使用 CustomPainter 作为父控件。我还实现了一个简单的逻辑,将第二个点作为 Offset 传递给画家。如果需要,您还可以传递一个简单的 boolean 变量来控制“绘制”和“清洁”状态。

import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Home(),
),
);
}

class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}

class _HomeState extends State<Home> {
Offset _offset = Offset(0, 0);

Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Draw Line'),
),
backgroundColor: Colors.white,
body: Column(
children: <Widget>[
SizedBox(
height: 200,
width: 200,
child: Container(),
),
CustomPaint(
foregroundPainter: LinePainter(_offset),
child: RaisedButton(
onPressed: () {setState(() {
_offset = Offset(60, 60);
});},
child: Text("Draw Line"),
),
)
],
),
);
}
}

class LinePainter extends CustomPainter {
Paint _paint;
Offset _offset;

LinePainter(Offset offset) {
_offset = offset;
_paint = Paint()
..color = Colors.amber
..strokeWidth = 8.0;
}

@override
void paint(Canvas canvas, Size size) {
canvas.drawLine(Offset(0, 0), _offset, _paint);
}

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

关于android - 点击按钮时如何在容器上画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973250/

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