![](/img/trans.png)
[英]Flutter : How to set dynamic color in CustomPainter object
[英]How can I change the color of a drawn object using CustomPainter in Flutter?
目前我有一個使用可觸摸的 CustomPainter flutter package
class MapPainter extends CustomPainter {
final BuildContext context;
MapPainter(this.context);
@override
void paint(Canvas canvas, Size size) {
var myCanvas = TouchyCanvas(context,canvas);
// Create a Paint object to draw the smiley face
var paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2.0;
// Draw the face
myCanvas.drawCircle(
Offset(size.width / 2, size.height / 2),
size.width / 2,
paint,
);
// Draw the eyes
myCanvas.drawCircle(
Offset(size.width * 0.25, size.height * 0.25),
size.width * 0.1,
paint,
onTapDown: (tapdetail) {
print("Touched");
}
);
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
OnTapDown 我希望能夠改變眼睛的顏色。
我是使用 CustomPainter 的新手,所以我不確定如何使用不同的 colors 重繪同一畫家,並且找不到使用可觸摸 package 的人這樣做。
首先,不要在內部傳遞context
,而是通過從parent傳遞具體數據來操作具體數據。
在您的情況下,集中數據是color
。
並嘗試使重新繪制盡可能最佳。 對於您的情況,僅當顏色已更改時才重新繪制。 以下是您的CustomPainter
的示例
class MapPainter extends CustomPainter {
final Color _eyeColor;
const MapPainter({Color? eyeColor}): _eyeColor = eyeColor ?? Colors.red;
@override
void paint(Canvas canvas, Size size) {
// Create a Paint object to draw the smiley face
var paint = Paint()
..color = _eyeColor
..style = PaintingStyle.stroke
..strokeWidth = 2.0;
// Draw the face
canvas.drawCircle(
Offset(size.width / 2, size.height / 2),
size.width / 2,
paint,
);
// Draw the eyes
canvas.drawCircle(
Offset(size.width * 0.25, size.height * 0.25),
size.width * 0.1,
paint
);
canvas.drawCircle(
Offset(size.width * 0.75, size.height * 0.25),
size.width * 0.1,
paint
);
}
@override
bool shouldRepaint(covariant MapPainter oldDelegate) {
return _eyeColor != oldDelegate._eyeColor;
}
}
要傳遞顏色,請使用StatefullWidget
:
class MyClickableWidget extends StatefulWidget {
const MyClickableWidget({Key? key}) : super(key: key);
@override
State<MyClickableWidget> createState() => _MyClickableWidgetState();
}
class _MyClickableWidgetState extends State<MyClickableWidget> {
final Color _oddColor = Colors.green;
final Color _evenColor = Colors.blue;
bool _isOdd = true;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() {
_isOdd = !_isOdd;
}),
child: CustomPaint(
painter: MapPainter(eyeColor: _isOdd ? _oddColor : _evenColor),
child: Container(),
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.