2

I'm using sprite from the flame package to show an image. I'm trying to add transparency, or opacity, to the image.

Here's my code:

void render(Canvas c) {
    Sprite spriteImg = Sprite('someImg.png');
    rect = Rect.fromLTWH(10, 10, 20, 20);
    spriteImg.renderRect(c, rect);
}

I can't seem to figure out how to add opacity.

Jessica
  • 9,379
  • 14
  • 65
  • 136

2 Answers2

4

You have to override the paint that is used when rendering, like this:

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

This will render your sprite with 50% opacity.

spydon
  • 9,372
  • 6
  • 33
  • 63
  • Is it possible to render a sprite so it appears lighter/darker instead of transparent/non transparent? – Going Bananas Aug 09 '21 at 10:26
  • 1
    @GoingBananas soon you will be able to use the `ColorEffect` to do that, once we release rc14 (which should be soon). – spydon Aug 10 '21 at 09:03
1
class NewComponent extends PositionComponent{
  static final Color _color = Color(0xFFFFFFFF);
  static final Paint _paint = Paint()
    ..color = _color
    ..style = PaintingStyle.fill;

  Sprite? sprite;

  Future<void> onLoad() async {
    sprite = await Sprite.load('image.png');
  }

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    final double colorOpacity = opacity.clamp(0, 1.0);
    _paint.color = _color.withOpacity(colorOpacity);
    sprite?.render(
      canvas,
      size: size,
      overridePaint: _paint,
    );
  }
}

Important details when updating transparency dynamically _paint.color = ? and opacity.clamp(0, 1.0)

QiXi
  • 59
  • 5