我的CustomPaoint大小为300,300。在此之下我还有其他小部件。我还有一个监听器,用于跟踪向下和移动位置,并将偏移量添加到列表中。此列表用于状态更改并发送到CustomPainter进行绘制。
一切正常。如果我在CustomPaint小部件的边界之外点击,那么它不会绘制。但是,如果我在CustomPaint中点击并移动到它之外,则Offsets是记录并用于绘画,这会导致在CustomPaint下面的其他小部件中绘画。
我该如何避免它?以下是我的代码。
class DrawingCanvas extends StatefulWidget {
@override
State<StatefulWidget> createState() => new DrawingCanvasState();
}
class DrawingCanvasState extends State<DrawingCanvas> {
GlobalKey _paintKey = new GlobalKey();
List<Offset> _finalOffsets = <Offset>[];
DrawingCanvasState() {
}
@override
Widget build(BuildContext context) {
return new Listener(
onPointerDown: (PointerDownEvent pdEvent) {
RenderBox referenceBox = _paintKey.currentContext.findRenderObject();
Offset localOffset = referenceBox.globalToLocal(pdEvent.position);
setState((){
this._finalOffsets.clear();
this._finalOffsets.add(localOffset);
});
},
onPointerMove: (PointerMoveEvent pmEvent) {
RenderBox referenceBox = _paintKey.currentContext.findRenderObject();
Offset localOffset = referenceBox.globalToLocal(pmEvent.position);
setState((){
this._finalOffsets.add(localOffset);
});
},
onPointerUp: (PointerUpEvent puEvent){
},
onPointerCancel: (PointerCancelEvent pcEvent){
},
child: new CustomPaint(
key: _paintKey,
size: new Size(300.0, 300.0),
isComplex: true,
willChange: true,
painter: new CanvasPainter(this._finalOffsets),
child: new ConstrainedBox(
constraints: new BoxConstraints.tightForFinite(width: 300.00, height: 300.00),
),
),
behavior: HitTestBehavior.deferToChild,
);
}
}
class CanvasPainter extends CustomPainter {
List<Offset> _offsets;
CanvasPainter(List<Offset> pOffsets){
this._offsets = pOffsets;
}
@override
void paint(Canvas canvas, Size size) {
Paint p = new Paint();
p.color = Colors.black;
p.strokeWidth = 5.0;
p.isAntiAlias = true;
p.style = PaintingStyle.stroke;
p.strokeJoin = StrokeJoin.round;
p.strokeCap = StrokeCap.round;
canvas.drawPoints(PointMode.polygon, this._offsets, p);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
// TODO: implement shouldRepaint https://stackoverflow.com/questions/45578209/how-to-touch-paint-a-canvas?rq=1
//print("should repaint check called");
return true;
}
}
注意 - DrawingCanvas用于另一个Column Widget。它下面有两个小部件。
请帮忙。