Search code examples
flutterdartspriteflame

How to Add transparency to image


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.


Solution

  • 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.