2

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?

denniswave
  • 127
  • 6

1 Answers1

1

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,
      ),
    ),
  );
spydon
  • 9,372
  • 6
  • 33
  • 63
  • Thanks! I'm still getting the hang of Flame, but it seems like to works a lot like SpriteKit with effects like these, yet it resembles the Flutter like structure. Pretty neat! Do you know if there's a way to 'permanently' color a `Sprite`? I don't really understand what the `Paint` object is doing on `SpriteComponent` if I can only seem to make it change alpha. – denniswave Feb 17 '22 at 21:00
  • 3
    You can try to do `paint.tint(color)`, that is basically what the `ColorEffect` is doing. – spydon Feb 17 '22 at 21:46
  • 1
    @spydon Tint is working great, but how about paint method, it seems not working. What is the usage for it? `MyComponent()..paint.color = Colors.red` <== not working – Davoud Apr 08 '22 at 11:56
  • I don't know what type of `Component` that your `MyComponent` is, but if you have only added the `HasPaint` mixin that doesn't do anything automatically, it just adds a `paint` field on your class that you can use for whatever you'd like. – spydon Apr 08 '22 at 17:16