【Android】Drawable sets the proportion of each color of Gradient

Drawable in Android sets the proportion of each color of Gradient

To set the gradient of an Android Drawable and specify the weight of each color, you can use the GradientDrawable class and set GradientDrawable.Orientation and a color array for it.

Here's a sample code that shows how to set up a gradient and specify the weight of each color:

// 定义渐变的方向
GradientDrawable.Orientation orientation = GradientDrawable.Orientation.LEFT_RIGHT;

// 定义渐变的颜色数组,每个颜色都可以指定比重
int[] colors = {
    
    Color.RED, Color.GREEN, Color.BLUE};
float[] colorPositions = {
    
    0.3f, 0.6f, 1.0f}; // 每个颜色的比重,取值范围为 0.0f 到 1.0f

// 创建 GradientDrawable 对象
GradientDrawable gradientDrawable = new GradientDrawable(orientation, colors);

// 设置渐变的颜色比重
gradientDrawable.setColors(colors);
gradientDrawable.setPositions(colorPositions);

// 应用 GradientDrawable 到一个 View 或者使用它作为 Drawable
view.setBackground(gradientDrawable);

In the above code, we first define the direction of the gradient (GradientDrawable.Orientation), where LEFT_RIGHT is used to represent the gradient from left to right.

Then, we define the gradient's color array (colors) and the specific gravity array of each color (colorPositions). In the example, we used red, green, and blue as color arrays, specifying a weight of 0.3f, 0.6f, and 1.0f for each color.

Next, we create a GradientDrawable object and pass in the gradient's direction and color array through the constructor. Then, use the setColors method to set the gradient's color array, and use the setPositions method to set the color's proportion array.

Finally, apply the GradientDrawable to a View or use it as a Drawable.

Guess you like

Origin blog.csdn.net/weixin_42473228/article/details/134191052