The CustomPainter lets you only draw shapes on the canvas. But most would want to let user interact with the drawings.
With touchable , you get what the normal canvas always missed : touchability
With this , its possible to add all kinds of gesture callbacks to each drawing and thus interaction capability to each Shape you draw on the canvas.
Animating individual shapes becomes so much easier than ever before.
Handles the painting style (filled ▮
, stroke ▯
) and detects touch accordingly.
Takes the painting stroke width also into account. So if your shapes are painted thick , we still got it covered ✓
Supports clipping and different clipping modes. So, You can have any kind of complex clipping and drawing combinations while getting full interactive capability.
Supports HitTestBehavior for each shape.
Simple and Easy API. Just wrap your CustomPaint
with CanvasTouchDetector
and use the TouchyCanvas
in your painter.
Add the touchable
package as dependency in your pubspec.yaml
dependencies:
touchable:
CustomPaint
widget with CanvasTouchDetector
. It takes a builder
function as argument that expects your CustomPaint
widget as shown below.CanvasTouchDetector(
builder: (context) =>
CustomPaint(
painter: MyPainter(context)
)
)
CustomPainter
class’s paint
method , create and use the TouchyCanvas
object (using the context
obtained from the CanvasTouchDetector and canvas
) to draw any shape with different gesture callbacks.var myCanvas = TouchyCanvas(context,canvas);
myCanvas.drawRect( rect , Paint() , onTapDown: (tapDetail){
//Do stuff here. Probably change your state and animate
});
class MyPainter extends CustomPainter {
final BuildContext context ;
MyPainter(this.context); // context from CanvasTouchDetector
@override
void paint(Canvas canvas, Size size) {
var myCanvas = TouchyCanvas(context,canvas);
myCanvas.drawCircle(Offset(10, 10), 60, Paint()..color=Colors.orange ,
onTapDown: (tapdetail) {
print("orange Circle touched");
},
onPanDown:(tapdetail){
print("orange circle swiped");
}
);
myCanvas.drawLine(
Offset(0, 0),
Offset(size.width - 100, size.height - 100),
Paint()
..color = Colors.black
..strokeWidth = 50,
onPanUpdate: (detail) {
print('Black line Swiped'); //do cooler things here. Probably change app state or animate
});
}
}
When you draw shapes on the canvas (TouchyCanvas
) , it keeps track of the dimensions of each shape you draw and their painting style , stroke etc.
When user performs any gesture on the screen , based on the location of the gesture , the appropriate shape is selected from the lot taking clipping regions , paint , hitTest behaviour etc into account in an optimized way. Callbacks of the corresponding shapes (one or more depending on the hitTest behavior) are executed.
StrokeCap.round
for lines with large widthAuthor: nateshmbhat
GitHub: https://github.com/nateshmbhat/touchable
#flutter #dart #mobile-apps