0

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);

    }
Delphian
  • 1,650
  • 3
  • 15
  • 31

1 Answers1

1

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.

Robbit
  • 4,300
  • 1
  • 13
  • 29
  • Joe, thank you it works. What do you think I can draw such a background with SweepGradient? – Delphian Nov 29 '17 at 09:13
  • 1
    Of course , use `SweepGradient(float cx, float cy, int[] colors, float[] positions)` this method to control the color change. – Robbit Nov 29 '17 at 09:20