How can I apply an alpha gradient on an image so that it fades linearly?
Right now, I'm creating rectangles of unit width and using it to draw the bitmap with a paint object with alpha value being changed in a loop. I only did it since I couldn't think of anything else. So a neater way would be better.
Bitmap bitmap = BitmapFactory.decodeStream(is);
Bitmap bmp = Bitmap.createScaledBitmap(bitmap, 100, 151, true));
bitmap.recycle();
Rect Rect1 = new Rect(0, 0, 100, 100);
Rect Rect2 = new Rect(100, 0, 101, 100);
Paint paint = new Paint();
canvas.drawBitmap(bmp, Rect1, Rect1, null);
while (paint.getAlpha() != 0) {
paint.setAlpha(paint.getAlpha() - 5);
canvas.drawBitmap(bmp, Rect2, Rect2, paint);
Rect2.set(Rect2.left + 1, Rect2.top, Rect2.right + 1, Rect2.bottom);
}
Something like this
P.S. I'm trying to do this for a live wallpaper.
Probably, desired behaviour could be meet with only views manipulations.
For it You should:
res/drawable/gradient_shape.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#00FFFFFF"
android:endColor="#FFFFFFFF"
android:type="linear" />
</shape>
Define layout: activity_main.xml:
<ImageView
android:id="@+id/photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/photo"
android:src="@drawable/gradient_shape" />
here drawable/photo is just jpeg in drawables folder;
Some suggests to add the following code to the activity (it, actually, depends on device native configuration and seems to be redundant for nowadays > 3.0 devices):
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
After that I've observed the following on my 4.1 device:
It looks like gradient. I'm still not sure if it's what You're looking for.