Pages

14 Mar 2014

Android - LinearGradient comprehension

Today I read about Property Animation, and I got into following snippet somehow.

TextView tv = (TextView) rootView.findViewById(R.id.textview);
tv.setText("I'm Leo");
tv.setWidth(150);
tv.setBackgroundColor(Color.BLACK);
LinearGradient linearGradient = new LinearGradient(0, 0, 150, 0,
        new int[]{
                Color.BLACK,
                Color.WHITE,
                Color.BLACK
        },
        new float[]{
                0,
                0.5f,
                1
        },
        Shader.TileMode.CLAMP);   
tv.getPaint().setShader(linearGradient);



At first, I couldn't figure out how does LinearGradient really work, especially the part position, why when:

new float[]{
        0,
        0.5f,
        1
},

is used, it gives a result like above picture?!

After an hour of trial-and-error, I realized that:
- The first number 0 means where the first Color.BLACK begins
- The second one, 0.5f means 50% of the width (0 to 150), so the Color.WHITE begins at where X = 75 (relatively with the TextView). And the TextView turns from Color.BLACK(X=0) to Color.WHITE(X=75)  within the part from X=0 to X=75
- Same things happen between the second one and the third one, TextView turns from Color.WHITE(X=75) to Color.BLACK(X=150) within the part from X=75 to X=150

Well, that's how the gradient is rendered as a great above picture, and if you work some more to integrate LinearGradient with Property Animation, you will get a great effect ;)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.