Drawing rectangles that fill up with gradient depending on the value

61
February 12, 2019, at 00:00 AM

I want to have three separate rectangles that would fill up with gradient. Depending on the value X the gradient would be placed differently. For example if value X = 75 the gradient would be 75% green and 25% red. I wanted to know if there is any library or a method that would allow me to do this in java (android studio).

Answer 1

To implement this, you could use LinearGradient for the gradient and then create a custom view with methods allowing you to change the layout of the gradient.

public class GradientView extends View {
     Paint paint;
     LinearGradient gradient;
     int[] colors = [Color.RED, Color.GREEN];
     public GradientView(Context context, int gradientHeight) {
          super(context);
          paint = new Paint();
          setGradientHeight(gradientHeight);
     }
     @Override
     protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        paint.setShader(colorGradient);
        canvas.drawPaint(paint);
    }
    public void setGradientHeight(int height){
        colorGradient = new LinearGradient(0, 0, 0, height * 0.01 * super.getHeight(), colors, null, Shader.TileMode.MIRROR);
        paint.setShader(colorGradient);
        invalidate();
    }
 }

Haven't tested the code, but it should certainly work something like this.

READ ALSO
Android Studio an generates error when creating an apk

Android Studio an generates error when creating an apk

I got the error specified below when I tried to generate the apk of my app in Android Studio ,please help

51
Different screen size issues - how to fix that?

Different screen size issues - how to fix that?

I have some fixed height and width, and margins in my layoutI think it is causing issue when I try to support multiple screen sizes

61
Please configure Android SDK Android Studio

Please configure Android SDK Android Studio

I am working with flutter and have the message Please configure Android SDK, I was looking at other answers but they don't fit, I click on configure and get the following imageYou can see its asking me for locations, I checked and they are correct

46
Getting wrong positions in Listview when scrolling

Getting wrong positions in Listview when scrolling

i'm using a customadapter for my listviewIn my Activity I have some Listeners to mark selcted Items (first time with log tap, then short tap) It works until the list becomes big enough to become scrollable

23