MfA tricks #10 - Vignette image effect
The original code comes from Romain Guy’s blog. Another person to follow for the Android graphics aficionado.
Today, we are going to see a really nice effect you can apply to your
ImageView that automatically adds rounded corners and extra shadowing to your displayed
These effects are based on a couple of
Shader classes like
ComposeShader so it’s also a nice introduction to them if you have never used any.
The code of the
Drawable wrapper that you use on your source
Usage of this class is pretty self-explanatory, together with the mandatory
Bitmap parameter you can set the corner radius and margin used to paint the image.
You can also turn off the shadowing step using the
withEffect parameter if it doesn’t go too well with your
Bitmap (which is generally the case when using icons with a dominant solid color).
When set up, use the
SetImageDrawable method of the
ImageView class to display the final result. Note that you need to give it a manual size for the code to behave correctly.
Below is an example instantiation:
Now for how it actually works. As mentioned before, we use two main shaders to do the magic for us.
First, we use
BitmapShader which takes a
Bitmap and transforms it into a texture that can be set as the source of a
Combined with the
DrawRoundRect method of
Canvas, it gives us a pain-free way to display our image with rounded corners without having to manually add them to the initial bitmap.
Then to create our halo effect, we use a gray-to-transparent
RadialGradient that is set to fill the bounds of our
That last shader is combined with the first one using a
ComposeShader which takes two shader objects and put them one over the other according to the specified Porter/Duff operator (in our case SourceOver meaning the halo is simply layered on top of the texture).
To show you the effect of the radial gradient on your image, here is a version where it’s applied on a solid color: