flutterdartspriteflame

How to recolour a Sprite


I am trying to figure out how to recolour or 'tint' a Sprite using the Flame engine for Flutter. I've tried to add or override a Paint object as described here: How to Add transparency to image.

Using the code below I tried changing the Paint object using a different color than white. The alpha does change, but my Sprite image stays white. My source image is a white png.

void render(Canvas c) {
  Sprite spriteImg = Sprite('someImg.png');
  rect = Rect.fromLTWH(10, 10, 20, 20);
  Paint redPaint = Paint()..color = Colors.red.withOpacity(0.5);
  spriteImg.renderRect(c, rect, overridePaint: redPaint);
}

The Flame engine must have a way to tint Sprites that I'm not seeing or using wrong right?


Solution

  • You can use a ColorEffect for that:

    yourSpriteComponent
      ..add(
        ColorEffect(
          Colors.red,
          const Offset(
            0.0,
            0.5,
          ), // Means, applies from 0% to 50% of the color
          EffectController(
            duration: 1.5,
          ),
        ),
      );