Home > Net >  flutter) How do I make arrow lines with canvas?
flutter) How do I make arrow lines with canvas?

Time:06-23

I want to put an arrow at the end (or on both sides) of a line drawn with a drawLine() of canvas.

Like this

enter image description here

Can I know how to do this?

CodePudding user response:

That's actually not that hard to do - there's just a little math involved.

Let's have a line and paint set up like this:

final paint = Paint()
  ..color = Colors.black
  ..strokeWidth = 2;

final p1 = Offset(50, 50);
final p2 = Offset(250, 150);

canvas.drawLine(p1, p2, paint); 

this will give us:

Now if we think of this line as a vector, we remember a vector has a direction. To get the direction we must find the angle between the start and the end of the line. This can be done using the atan2 function of dart's math library.

So import the math library

import 'dart:math' as math;

and add the following lines

final dX = p2.dx - p1.dx;
final dY = p2.dy - p1.dy;
final angle = math.atan2(dY, dX);

Afterwards let's determine a size and an angle for the arrow we're about to put at the end of the line:

final arrowSize = 15;
final arrowAngle=  25 * math.pi / 180;

Everything that's left is actually drawing the arrow. This is basically done by drawing a triangle at the proper angle the line is facing using a path.

final path = Path();

path.moveTo(p2.dx - arrowSize * math.cos(angle - arrowAngle),
    p2.dy - arrowSize * math.sin(angle - arrowAngle));
path.lineTo(p2.dx, p2.dy);
path.lineTo(p2.dx - arrowSize * math.cos(angle   arrowAngle),
    p2.dy - arrowSize * math.sin(angle   arrowAngle));
path.close();
canvas.drawPath(path, paint);

Which will finally give us:

  • Related