How to Make a PNG Gradient Overlay in Flutter
Hi everyone! Oleh Nahornyi, one of our mobile developers and Flutter fan, has conducted great research on how to apply a gradient to a png-image with alpha channel. Thus, we would like to share his results with you. Here is what we are talking about:
Basically, it is easy to impose a particular color on the png image. All you have to do is the following:
In this case, you will come up with such a result:
But if you need to apply a gradient, the first idea which anyone, who is even slightly familiar with Flutter might have, is to use BoxDecoration in the Container:
And this is what we get:
We expected a different result, but perhaps it might be useful when you need to put the color as a background of the png.
Also, you can find out about various options regarding superposition of colors and pictures in the amazing article by Julien Louage.
So any developer who faced similar problems would start to research the source code in the Image class https://docs.flutter.io/flutter/widgets/Image-class.html. However, in this class, there is not even the slightest hint of gradient application. Still, there is such an interesting parameter as BlendMode.
If you refer to the BlendMode documentation https://docs.flutter.io/flutter/dart-ui/BlendMode-class.html, you can actually find what we need:
Coming back to our example with BoxDecoration, we add BlendMode.dstAtTop, but for Image, we can add the only colorBlendMode.
Applying such an approach this is what we get:
Well, our destination is our picture, it probably worths trying BlendMode.dstOver:
The result is the same, BlendMode, in this case, is applied to the color which should be set in Image.
How, then, to use BlendMode to apply a gradient?
Is there a class in Flutter that would contain gradient parameters, Image, and BlendMode?
After a long search, we found such a class (perhaps there are other classes with a similar feature. If you know them, share them in comments, please).
ShaderMask class (https://docs.flutter.io/flutter/widgets/ShaderMask-class.html) creates a widget which applies a mask generated by a Shader to its child. It has all required blendMode and shaderCallback parameters, which we need to apply a gradient. There is also a child parameter through which we can set our Image.
The final completed code looks like this:
We hope this article helped you solve the problem. A full example is available at
Contribute to oleeja/FlutterGradientExample development by creating an account on GitHub.github.com
Happy Coding :)