簡體   English   中英

如何使用Android GradientDrawable

[英]How to use Android GradientDrawable

我嘗試使用GradientDrawable為某些背景和按鈕設置漸變。 不幸的是, 文檔不是很詳細。

配置漸變的主要屬性是什么? 我了解開始和結束色,但其他一些屬性可能需要一些解釋。

目前,我使用圖像作為按鈕的背景,但是用XML定義的可繪制對象會更好。

我嘗試看起來像這樣(漸變非常淺): 替代文字http://janusz.de/~janusz/RedButton.png

使用此xml作為imageview的背景。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="90" android:startColor="#7c0000" android:endColor="#A71C1C"/>
</shape>

而已。

我將給出與Praveen相同的答案,但還將嘗試解釋這些設置。

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient 
       android:type="linear" 
       android:angle="-90" 
       android:startColor="#7c0000" 
       android:endColor="#A71C1C" />
</shape>

android:類型

共有3種漸變類型,默認設置為漸變,該問題的一種為“線性”。 另外兩個是“徑向”和“掃掠”。

android:角度

梯度的逆時針旋轉,其中0為| 起始顏色->結束顏色| (水平)。

android:startColor

漸變開始的顏色,開始由旋轉定義。

android:endColor

用漸變結束的顏色,結束由旋轉定義。

android:centerColor

如果需要,在開始和結束顏色之間也可以有顏色。

在此處輸入圖片說明

我最初發現這個問題是因為我想用代碼來實現。 這是通過編程方式進行的方法。

int startColor = 0xfff6ee19; // yellow
int endColor = 0xff115ede;   // blue
GradientDrawable gradientDrawable = new GradientDrawable(
        GradientDrawable.Orientation.LEFT_RIGHT,
        new int[] {startColor, endColor});

View myView = findViewById(R.id.my_view);
myView.setBackgroundDrawable(gradientDrawable);

頂部圖像中的不同方向可以通過更改構造函數中的“ Orientation來實現。

XML格式

正如已經回答的那樣,這就是您在xml中執行的操作。

my_gradient_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="0"
        android:startColor="#f6ee19"
        android:endColor="#115ede" />
</shape>

您將其設置為某些視圖的背景。 例如:

<View
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:background="@drawable/my_gradient_drawable"/>

也可以看看

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM