1. ホーム
  2. android

Androidのカラーグラデーション実装のまとめ

2022-02-17 19:10:19
<パス

前文

日常のAndroid開発では、カラーグラデーションの大部分を使う必要があります。UIが対応する画像リソースのセットを提供してくれることもあるので、それを直接使うこともできますが、もちろん、コードを通して自分でカラーグラデーションを実装することもできます:それは

I. XMLでカラーグラデーションを実装する

比較的簡単です 対応するShapeファイルをカスタマイズし、そのプロパティを設定し、android:backgroundとして対応するViewに直接割り当てることで、カラーグラデーションを実装しています。

1. XMLファイルの作成

にあるdrawableフォルダにshapeリソースを作成します。

形状_グラデーション.xml ファイルコードは以下の通りです。


各レベルのタグを説明する。

<ブロッククオート

[shape] ルートタグ、シェイプの宣言
[グラデーション] コーナー、ストローク、サイズなどの他の属性に加えて、シェイプのグラデーションカラーの属性を宣言します。
[android:angle] グラデーションカラーの角度。例えば、上から下へのカラーグラデーションは0、左から右へのカラーグラデーションは45、下から上へのカラーグラデーションは90...といった具合です。
[android:startColor&android:endColor] はよくわかる、フェード開始時の色とフェード終了時の色(何色から何色へ)。

2. 対応するViewにグラデーションカラーを付与する

MainActivityのレイアウトファイルに直接記述する。

3. Run to see the results
In the image below, the area marked within the red border is the area of the gradient color.
Second, code to implement the color gradient
The above approach can actually handle more than 80% of color gradients, but sometimes we want to implement more complex color gradients, such as
1. Multiple gradients (color1 -> color2 -> ... ->colorN) 

2. Draw in custom View
3. More other complex requirements This is where we can customize the effect we want with the LinearGradient class, using a small demo to illustrate. In this demo, our main interface color gradient is (pink -> gray -> blue)
1. Introduction to the LinearGradient class The usage is very simple.
 /** Create a shader that draws a linear gradient along a line.
      @param x0 The x-coordinate for the start of the gradient line
      @param y0 The y-coordinate for the start of the gradient line
      @param x1 The x-coordinate for the end of the gradient line
      @param y1 The y-coordinate for the end of the gradient line
      @param colors The colors to be distributed along the gradient line
      The relative positions [0..1] of
                          The relative positions [0..1] of each corresponding color in the colors array,
                          If this is null, the the colors are distributed evenly along the gradient line.
      @param tile The Shader tiling mode
  */@param tile
   public LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[],
           TileMode tile) 
 /**
    @param x0 X coordinate of the start point
    @param y0 y-coordinate of the start point
    @param x1 X coordinate of the end point
    @param y1 End point Y coordinate
    @param colors the set of all color gradients
    @param positions We can make it a uniform gradient, or we can make it a gradient in the ratio you want, which can be null, so that assuming 1 is the entire length of the gradient, all the colors we set (assuming there are 4 colors), are graded with equal weight (gradient length ratio 0.25:0.25:0.25:0.25).
    @param tile Different modes of the shader
 */
public LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[],
           TileMode tile) 
As you can see. To implement it, we need to determine two coordinates, the start coordinate -> the end coordinate, and the set of all the colors to be graded, as well as the coordinates of the point where the colors will be rotated (position[]), and finally, the tileMode. For more details on the different modes of shaders, see this article if you need it. An introduction to using the shader LinearGradient 2. Customizing the View: public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } super(context, attrs); } public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs); } super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //Get the width and height of the View int width = getWidth(); int height = getHeight(); int colorStart = getResources().getColor(R.color.colorPrimary); int color1 = Color.GRAY; int colorEnd = getResources().getColor(R.color.colorAccent); Paint paint = new Paint(); LinearGradient backGradient = new LinearGradient(0, 0, 0, height, new int[]{colorStart, color1 ,colorEnd}, null, Shader.TileMode.CLAMP); paint.setShader(backGradient); canvas.drawRect(0, 0, width, height, paint); } } Then we put our custom view into the MainActivity layout file, and you can see the effect above!
3. Careful analysis of a wave
The code should be easy to understand, so let's review the construction of LinearGradient and see how the color gradient in the direction (top to bottom in this case) is achieved
LinearGradient(0, 0, 0, height, new int[]{colorStart, color1 ,colorEnd}, null, Shader.TileMode.CLAMP);
Can't we understand from the diagram that it's actually a color gradient in 2 coordinates, with the color gradient direction specified by the x1,y1 -> x2,y2 coordinates!
So what if we want to achieve a 45° diagonal color gradient? Isn't it simple enough that the coordinates go from (0, 0) to (width, height)? Let's try.
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //Get the width and height of the View
        int width = getWidth();
        int height = getHeight();

        int colorStart = getResources().getColor(R.color.colorPrimary);
        int color1 = Color.GRAY;
        int colorEnd = getResources().getColor(R.color.colorAccent);

        Paint paint = new Paint();
        LinearGradient backGradient = new LinearGradient(0, 0, width, height, new int[]{colorStart, color1 ,colorEnd}, null, Shader.TileMode.CLAMP);
// LinearGradient backGradient = new LinearGradient(0, 0, 0, height, new int[]{colorStart, color1 ,colorEnd}, null, Shader;)
        paint.setShader(backGradient);
        canvas.drawRect(0, 0, width, height, paint);
    }
Get the result.
Finally, the source code portal is placed at
GitHubu source code portal - click me click me
/** Create a shader that draws a linear gradient along a line. @param x0 The x-coordinate for the start of the gradient line @param y0 The y-coordinate for the start of the gradient line @param x1 The x-coordinate for the end of the gradient line @param y1 The y-coordinate for the end of the gradient line @param colors The colors to be distributed along the gradient line The relative positions [0..1] of The relative positions [0..1] of each corresponding color in the colors array, If this is null, the the colors are distributed evenly along the gradient line. @param tile The Shader tiling mode */@param tile public LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[], TileMode tile) /** @param x0 X coordinate of the start point @param y0 y-coordinate of the start point @param x1 X coordinate of the end point @param y1 End point Y coordinate @param colors the set of all color gradients @param positions We can make it a uniform gradient, or we can make it a gradient in the ratio you want, which can be null, so that assuming 1 is the entire length of the gradient, all the colors we set (assuming there are 4 colors), are graded with equal weight (gradient length ratio 0.25:0.25:0.25:0.25). @param tile Different modes of the shader */ public LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[], TileMode tile)