Android平台下實現漸層效果

來源:互聯網
上載者:User

 Android平台下實現漸層效果。在android.graphics中我們可以找到有關Gradient字樣的類,比如LinearGradient 線性漸層、RadialGradient放射狀漸層和 角度漸層SweepGradient 三種,他們的基類為android.graphics.Shader。為了顯示出效果,使用一個簡單的例子來說明。

一、LinearGradient線性漸層

在android平台中提供了兩種重載方式來執行個體化該類分別為,他們的不同之處為參數中第一種方法可以用顏色數組,和位置來實現更細膩的過渡效果,比如顏色採樣int[] colors數組中存放20種顏色,則漸層將會逐一處理。而第二種方法參數僅為起初顏色color0和最終顏色color1。

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)
使用執行個體如下:
Paint p=new Paint();
LinearGradient lg=new LinearGradient(0,0,100,100,Color.RED,Color.BLUE,Shader.TileMode.MIRROR);  //參數一為漸層起初點座標x位置,參數二為y軸位置,參數三和四分辨對應漸層終點,最後參數為平鋪方式,這裡設定為鏡像.

剛才Android開發網已經講到Gradient是基於Shader類,所以我們通過Paint的setShader方法來設定這個漸層,代碼如下:
p.setShader(lg);
canvas.drawCicle(0,0,200,p); //參數3為畫圓的半徑,類型為float型。

二、 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)

三、 SweepGradient角度漸層

對於一些3D立體效果的漸層可以嘗試用角度漸層來完成一個圓錐形,相對來說比上面更簡單,前兩個參數為中心點,然後通過載入的顏色來平均的漸層渲染。

SweepGradient(float cx, float cy, int[] colors, float[] positions)  //對於最後一個參數SDK上的描述為May be NULL. The relative position of each corresponding color in the colors array, beginning with 0 and ending with 1.0. If the values are not monotonic, the drawing may
produce unexpected results. If positions is NULL, then the colors are automatically spaced evenly.,所以Android123建議使用下面的重載方法,本方法一般為NULL即可。
SweepGradient(float cx, float cy, int color0, int color1)

或者直接建立一個drawable:

  GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
    new int[] { Color.BLACK, Color.WHITE });
  this.getWindow().setBackgroundDrawable(grad);

 

本文轉載自:http://xxw8393.blog.163.com/blog/static/37256834201072655832696/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.