2012-08-28 34 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; 
    }