Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

Horizontal LinearGradient with android

This must be an easy one but I'm really at a loss... The following code draws a rectangle with a linear gradient going from left to right, from white to black,

int x1 = 0, y1 = 0, x2 = 100,  y2 = 40;
Shader shader = new LinearGradient(x1, y1, x2, y2, Color.WHITE, Color.BLACK, TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
canvas.drawRect(new RectF(x1, y1, x2, y2), paint);

Ok, fine. Now what I'd like to do is to change this gradient into a horizontal one, so that the color goes from white to black, from top to bottom. What I tried to do is to add:

Matrix trans = new Matrix();
trans.setRotate(90);
shader.setLocalMatrix(trans);

but instead the gradient goes at a funny angel, or there is just a single color... I also tried to play with the coordinates of the gradient in all sorts of way (thinking that maybe they should be transformed) to no avail. What am I missing?

question from:https://stackoverflow.com/questions/3999839/horizontal-lineargradient-with-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I haven't done much android coding, but one approach worth trying is:

int x1 = 0, y1 = 0, x2 = 0,  y2 = 40;

The x never changes in the gradient only the y does.

So what this might look like is:

Shader shader = new LinearGradient(0, 0, 0, 40, Color.WHITE, Color.BLACK, TileMode.CLAMP);
Paint paint = new Paint(); 
paint.setShader(shader); 
canvas.drawRect(new RectF(0, 0, 100, 40), paint); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...