flutterdartcustom-painting

CustomPaint drawLine cannot apply transparency on lines drawn


I was trying to use alpha channel to apply transparency on line colors with CustomPaint's Canvas.drawLine().

Problem

However, the color tweaks on alpha channel takes no effect on the results, for example, the following code still gives me 100% opaque white lines


  final gridPaint = Paint()
    ..strokeJoin = StrokeJoin.miter
    ..strokeWidth = 1.0
    ..color = const Color(0xe6ffffff)
    ..style = PaintingStyle.stroke;


  canvas.drawLine(start, end, gridPaint);

Workaround

I have to draw 1-pixel-wide drawRect to get transparent lines.

Question

Is this by design?


Solution

  • You can use the withOpacity method on the color of your choice.

    Colors.green.withOpacity(0.5)
    

    or

    Color(0xe6ffffff).withOpacity(0.5)
    

    Set the value to a number from 0 to 1 depending on the level of opacity you wish to achieve.