Reputation: 83
I want to make a custom view for my android app which has a functionality to change its background colour "gradient".
Something like this, but the centre handle can be moved left and right using code
The catch is that I want a function something like in the view:
changeBackgroundGradient(ratio, startColour, centreColour, endColour);
ratio (having value between 0 to 1) which is given by formula leftValue/rightValue determining the shape of the gradient
startColour, centreColour and endColour being the colours of which the gradient consists of
How would i make this function?
Regards
Upvotes: 1
Views: 675
Reputation: 6067
You can try below code as this is working for me to change my toolbar color dynamically
private void setGradientColor(View header)
{
String primaryColor = "#f4f3f2"; // any color code
String primaryDarkColor = "#000000";
GradientDrawable gd = new GradientDrawable (
GradientDrawable.Orientation.BR_TL, // check below link for this you can change this value
new int[] {
Color.parseColor(primaryColor),
Color.parseColor(primaryDarkColor)
}
);
gd.setCornerRadius(1f);
header.setBackground(gd);
}
Update
Check this for more options to apply gradient color in view.
Upvotes: 0
Reputation: 5684
You can try following function. Add these functions in your activity file.
private Drawable getGradientDrawable()
{
GradientDrawable gradient = new GradientDrawable();
gradient.setGradientType(GradientDrawable.LINEAR_GRADIENT);
gradient.setColors(new int[]{getRandomHSVColor(), getRandomHSVColor()});
return gradient;
}
protected int getRandomHSVColor(){
// Generate a random hue value between 0 to 360
int hue = mRandom.nextInt(361);
// We make the color depth full
float saturation = 1.0f;
// We make a full bright color
float value = 1.0f;
// We avoid color transparency
int alpha = 255;
// Finally, generate the color
int color = Color.HSVToColor(alpha, new float[]{hue, saturation, value});
// Return the color
return color;
}
// Custom method to get a lighter color
protected int getLighterColor(int color){
float[] hsv = new float[3];
Color.colorToHSV(color,hsv);
hsv[2] = 0.2f + 0.8f * hsv[2];
return Color.HSVToColor(hsv);
}
// Custom method to get reverse color
protected int getReverseColor(int color){
float[] hsv = new float[3];
Color.RGBToHSV(
Color.red(color), // Red value
Color.green(color), // Green value
Color.blue(color), // Blue value
hsv
);
hsv[0] = (hsv[0] + 180) % 360;
return Color.HSVToColor(hsv);
}
Than use this function like below:
your_layout_name..setBackground(getGradientDrawable());
Upvotes: 0