Android - how to draw 2-directional gradient?

2019-02-28 04:27发布

I started playing with gradients and I've found it's pretty easy to draw 1-directional gradient (like from top to bottom, from left to right, or in diagonale...) but how to draw 2-directional gradient? I mean something like this:

enter image description here

Big blue rectangle it's 2-directional gradient - on top right corner there is blue and to the left its transforming to white and to the bottom it's transforming to the black. How to draw this?

2条回答
对你真心纯属浪费
2楼-- · 2019-02-28 04:44

You can do something like this when you create your gradient color:

 <gradient
    android:centerColor="@color/my_white"
    android:startColor="@color/my_darker_gray"
    android:endColor="@color/my_darker_gray"
    android:angle="45"/>

Specify the color you desire for the start/end/center location of the gradient, and specify the angle of the color switching.

查看更多
可以哭但决不认输i
3楼-- · 2019-02-28 04:56

Answer is: you must combine 2 different LinearGradients, for example:

LinearGradient val = new LinearGradient(0, 0, 0, height, Color.WHITE, Color.BLACK, TileMode.CLAMP);
                LinearGradient sat = new LinearGradient(0, 0, width, 0, Color.WHITE, Color.HSVToColor(hsvCopy), TileMode.CLAMP);
                ComposeShader merged = new ComposeShader(val, sat, PorterDuff.Mode.MULTIPLY)

;

And of course important:

[view with this background].setLayerType(View.LAYER_TYPE_SOFTWARE, null);

on phones with 3.0 android and higher

查看更多
登录 后发表回答