2012-08-28 32 views
53

我正在通過測試示例。當他們正在使用漸變一些圖片的背景, 的代碼是這樣android漸變中的角度屬性

<?xml version="1.0" encoding="utf-8"?> 


    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <gradient 
     android:startColor="#ff0000" 
     android:centerColor="#00ff00" 
     android:endColor="#0000ff" 
     android:angle="180"/> 
    <corners android:radius="5dp" /> 
    </shape> 

在上面的XML我沒有得到angle屬性。但是當我稍微改變angle的值時,模式就會偏離。任何人都可以解釋我的工作原理........... :)

回答

120

漸變基本上代表任何數量的空間變化(在一個方向上)。用顏色表示顏色強度在由角度表示的方向上的變化。下面是一些圖表來表示這個概念:
enter image description here

這裏的圖顯示了水平方向上的顏色變化(角度設置爲0)。
XML代碼:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <gradient 
     android:startColor="#000000" 
     android:angle="0"/> 
    </shape> 

enter image description here

在這裏,圖示出了在水平方向上的顏色變化(角度被設定90)。
XML代碼:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<gradient 
    android:startColor="#000000" 
    android:angle="90"/> 
</shape> 

您還可以使用不同的顏色作爲開始,中心和邊緣的顏色。您附加的代碼包含所有這些元素。

+17

謝謝回答卡恩,但有一件事我發現我可以給角屬性的45只倍數,比它崩潰即其他20,20,50等 –

+0

方法有很多種,其中梯度可表達。這裏我們實際上是使用線性梯度(沿着直線斜率m =(y-y1)/(x-x1))的斜率。當它是45的倍數時,x和y的變化是相同的。可能是這個原因的原因。我不太瞭解。 – karn

+4

極好地使用插圖解釋這個! – Ralphleon

3

指定形狀的漸變顏色。 屬性:

android:角度 整數。漸變的角度,以度爲單位。 0從左到右,90從下到上。它必須是45的倍數。默認爲0.

似乎文檔中的描述與卡恩的答案相矛盾?

您可以找到documentation

4

更多的細節,你可能想創建代碼對角線梯度。這很容易,你有很多選擇從那裏打開。這個片段讓我

public void SetGradient(View view) { 
     GradientDrawable gd = new GradientDrawable(
       GradientDrawable.Orientation.TL_BR, 
       new int[]{0xFF141a24, 0xFF293f49, 0xFF72554c}); 
     view.setBackground(gd); 
    } 

可用方向從GradientDrawable類

/*public enum Orientation { 
     *//** draw the gradient from the top to the bottom *//* 
     TOP_BOTTOM, 
     *//** draw the gradient from the top-right to the bottom-left *//* 
     TR_BL, 
     *//** draw the gradient from the right to the left *//* 
     RIGHT_LEFT, 
     *//** draw the gradient from the bottom-right to the top-left *//* 
     BR_TL, 
     *//** draw the gradient from the bottom to the top *//* 
     BOTTOM_TOP, 
     *//** draw the gradient from the bottom-left to the top-right *//* 
     BL_TR, 
     *//** draw the gradient from the left to the right *//* 
     LEFT_RIGHT, 
     *//** draw the gradient from the top-left to the bottom-right *//* 
     TL_BR, 
    }*/ 

,並調用從的onCreate或onCreateView在片段的方法,並通過父視圖(對我來說)。

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.dialog_view_parent, container);   
     ... 

     SetGradient(view); 

     return view; 
    }