Android開發之漸變色,你學會了嗎?
android.graphics中提供了有關Gradient類,包含LinearGradient線性漸變、 RadialGradient徑向漸變和SweepGradient梯度漸變,它們的繼承自android.graphics.Shader。
LinearGradient 線性漸變
LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)
LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile)
參數 | 說明 |
x0 | 漸變線起點的x坐標 |
y0 | 漸變線起點的y坐標 |
x1 | 漸變線末端的x坐標 |
y1 | 漸變線末端的y坐標 |
colors | 沿著漸變線分布的顏色數組 |
color0 | 漸變線開始處的顏色 |
color1 | 漸變線末端的顏色 |
positions | 顏色數組中每個對應顏色的相對位置[0,1]。如果為null,則顏色沿線均勻分布 |
tile | 著色器平鋪模式 |
Paint paint =new Paint();
//兩個坐標形成變量,規定了漸變的方向和間距大小,著色器為鏡像
LinearGradient linearGradient =new LinearGradient(0,0,200,0, Color.RED,Color.BLUE, Shader.TileMode.MIRROR);
paint.setShader(linearGradient);
paint.setStrokeWidth(50);
canvas.drawLine(0,getMeasuredHeight()/2,getMeasuredWidth(),getMeasuredHeight()/2, paint);
圖片
RadialGradient 徑向/放射漸變
RadialGradient(float x, float y, float radius, int[] colors, float[] positions, Shader.TileMode tile)
RadialGradient(float x, float y, float radius, int color0, int color1, Shader.TileMode tile)
參數 | 說明 |
x | 半徑中心的x坐標 |
y | 半徑中心的y坐標 |
radius | 漸變的圓的半徑 |
colors | 顏色分布在圓的中心和邊緣之間 |
color0 | 圓圈中心的顏色 |
color1 | 圓圈邊緣的顏色 |
positions | 顏色數組中每個對應顏色的相對位置[0,1]。如果為null,則顏色沿線均勻分布 |
tile | 著色器平鋪模式 |
paint =new Paint();
radialGradient =new RadialGradient(240,360,200, new int[]{Color.BLUE, Color.GREEN, Color.RED },null, Shader.TileMode.CLAMP);
paint.setShader(radialGradient);
canvas.drawCircle(240,360,200,paint);
圖片
SweepGradient 掃描/梯度/扇形漸變
SweepGradient(float x, float y, int[] colors, float[] positions)
SweepGradient(float x, float y, int color0, int color1)
參數 | 說明 |
x | 中心的x坐標 |
y | 中心的y坐標 |
colors | 顏色分布在中心周圍,陣列中必須至少有2種顏色 |
color0 | 掃描開始時使用的顏色 |
color1 | 掃描結束時使用的顏色 |
positions | 顏色數組中每個對應顏色的相對位置[0,1]。如果為null,則顏色沿線均勻分布 |
paint =new Paint();
int[] colors = new int[]{Color.GREEN, Color.GREEN, Color.BLUE, Color.RED, Color.RED};
sweepGradient = new SweepGradient(240, 360,colors,null);
paint.setShader(sweepGradient);
canvas.drawCircle(x,y,200,paint);
圖片