Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal LinearGradient with android

Tags:

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?

like image 571
akoprowski Avatar asked Oct 22 '10 18:10

akoprowski


People also ask

What is gradient drawable?

Designers are trying out different styles and combinations which go best with the Android App. One of the key components of Android being used these days is called GradientDrawable. A GradientDrawable is drawable with a color gradient for buttons, backgrounds, etc.


2 Answers

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);  
like image 90
Graeme G Avatar answered Sep 20 '22 18:09

Graeme G


you can adjust the gradient orienation

Top to Bottom

LinearGradient(0, 0, 0, height, gradientStartColor, gradientEndColor, Shader.TileMode.CLAMP) 

Bottom to Top

LinearGradient(0, height, 0, 0, gradientStartColor, gradientEndColor, Shader.TileMode.CLAMP) 

Left to Right

LinearGradient(0, 0, width, 0, gradientStartColor, gradientEndColor, Shader.TileMode.CLAMP) 

Right to Left

LinearGradient(width, 0, 0, 0, gradientStartColor, gradientEndColor, Shader.TileMode.CLAMP) 
like image 22
venkatesh Avatar answered Sep 20 '22 18:09

venkatesh