As you may know it is not possible to draw an oval radial gradient using regular Android API.
This is what I want to achieve:
So I implemented this solution: draw a regular radial gradient on a square bitmap and then this bitmap will get stretched by the view itself (idea found here: https://mcmap.net/q/738626/-oval-gradient-in-android)
This works great however this solution takes a lot of memory, because of BitmapDrawable usage (see implementation details below).
Any ideas on how to avoid usage of such a big bitmap are welcome!
This my code:
public class OvalGradientView extends ImageView {
private Drawable defaultBackgroundDrawable;
public OvalGradientView(Context context) {
super(context);
init();
}
public OvalGradientView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public OvalGradientView(Context context, AttributeSet attrs, int defStyleAttr, Paint paint) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setScaleType(ScaleType.FIT_XY);
defaultBackgroundDrawable = getResources().getDrawable(R.drawable.default_background);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int width = getWidth();
int height = getHeight();
Rect currentBounds = defaultBackgroundDrawable.getBounds();
// check if we already have bitmap for these bounds
if (currentBounds.right == width && currentBounds.bottom == height) {
return;
}
// draw the drawable on square bitmap, it will be then stretched if needed to rectangular shape
// as the view gets more rectangular
defaultBackgroundDrawable.setBounds(0, 0, width, width);
Bitmap defaultBackgroundBitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(defaultBackgroundBitmap);
defaultBackgroundDrawable.draw(canvas);
setImageBitmap(defaultBackgroundBitmap);
}
}
And this is the drawable XML - default_background
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#ffffff"
android:endColor="#ff6600"
android:gradientRadius="50%p"
android:type="radial" />
</shape