1. 程式人生 > >自定義shape實現Button和Textview的圓角,描邊,顏色漸變效果

自定義shape實現Button和Textview的圓角,描邊,顏色漸變效果

shape特效定製很重要,但不經常用容易忘記,所以記錄在這裡方便以後需要時直接來看筆記,只因為本人不喜歡背程式碼,只喜歡活學活用吧!哈哈
實現效果如下圖中按鈕的樣式,有邊框描邊,有中間背景顏色過渡漸變,有四個圓角效果:

實現很簡單,只需兩個步驟就行:
第一步:在res目錄下的drawable目錄中建立一個btn_custom_bg_shape.xml檔案,並寫入如下程式碼:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--描邊--> <stroke android:width="2dp" android:color="#ffffff" /> <!--圓角度數--> <corners android:radius="145dp"/> <!--顏色填充--> <!--<solid android:color="#000000"/>--> <!--背景顏色漸變過渡,可以設定開始和結束的顏色漸變效果-->
<gradient android:startColor="#541298" android:endColor="#541298"/> </shape>

第二步:在想要這樣效果的控制元件中引入該shape檔案作為background屬性值,佈局layout和button,textview都可以這樣應該。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical"> ... <Button android:layout_width="match_parent" android:layout_height="@dimen/dp_35" android:layout_marginLeft="@dimen/dp_42" android:layout_marginRight="@dimen/dp_42" android:textSize="@dimen/sp_17" android:layout_marginTop="@dimen/dp_11" android:layout_marginBottom="@dimen/dp_11" android:background="@drawable/btn_custom_bg_shape" android:textColor="@color/white" android:text="CHECK COMPATIBILITY"/> ... </LinearLayout>

到這裡就基本實現了想要的自定義shape實現控制元件的圓角,描邊,顏色漸變展示效果了!