Search code examples
androidandroid-layoutandroid-backgroundsweepgradient

Layout background with SweepGradient


I need to create a multicolor background like in the picture. I know all colors and angles.

enter image description here

I try to do this with SweepGradient, but nothing change, I see only white background.

A piece of my layout

<RelativeLayout
    android:id="@+id/user_info_background"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

Code in fragment:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mRelativeLayout.setBackground(GraphicalUtils.addSweepGradientBackground(getResources().getDisplayMetrics().widthPixels, 
    getResources().getDisplayMetrics().heightPixels,getContext()));}

Method for adding SweepGradient:

 public static Drawable addSweepGradientBackground(int width, int height, Context context){
        Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas();

        SweepGradient sweepGradient = new SweepGradient(width/2,height/2,Color.RED, Color.BLUE);

        Paint paint = new Paint();
        paint.setShader(sweepGradient);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        canvas.drawBitmap(bitmap,0,0,paint);

        return new BitmapDrawable(context.getResources(), bitmap);

    }

Solution

  • Try this:

    public static Drawable addSweepGradientBackground(int width, int height, Context context){
        Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
    
        SweepGradient sweepGradient = new SweepGradient(width/2,height/2,Color.RED, Color.BLUE);
    
        Paint paint = new Paint();
        paint.setShader(sweepGradient);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        canvas.drawBitmap(bitmap,0,0,null);
        canvas.drawCircle(width/2,height/2, width/2, paint)
    
        return new BitmapDrawable(context.getResources(), bitmap);
    
    } 
    

    the canvas should be bound with bitmap ,and you need draw the circle with the paint which has sweepGradient on the bitmap.