目錄

目錄
GradientDrawable是什么
GradientDrawable在Android中便是shape標(biāo)簽的代碼實(shí)現(xiàn),利用GradientDrawable也可以創(chuàng)建出各種形狀。
GradientDrawable使用方法
1. 獲取控件的shape并進(jìn)行動(dòng)態(tài)修改:
既然GradientDrawable是shape的動(dòng)態(tài)實(shí)現(xiàn),那么他就可以通過(guò)動(dòng)態(tài)的獲取控件的shape獲取實(shí)例并進(jìn)行修改,例如動(dòng)態(tài)改變一個(gè)矩形shape的顏色并添加圓角:

布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.itfitness.drawabledemo.MainActivity">
<Button
android:text="Change"
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<View
android:id="@+id/view"
android:background="@drawable/shape_rect"
android:layout_width="300dp"
android:layout_height="300dp" />
</LinearLayout>
shape_rect.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/colorAccent"/>
</shape>
java代碼中進(jìn)行動(dòng)態(tài)修改
GradientDrawable background = (GradientDrawable) view.getBackground();//獲取對(duì)應(yīng)的shape實(shí)例
background.setColor(Color.GREEN);//設(shè)置為綠色
background.setCornerRadius(20);//設(shè)置圓角
view.setBackgroundDrawable(background);
2. 通過(guò)代碼動(dòng)態(tài)創(chuàng)建:
//什么都不指定默認(rèn)為矩形
GradientDrawable background = new GradientDrawable();
background.setColor(Color.GREEN);
view.setBackgroundDrawable(background);

如果想要設(shè)置形狀的話可以通過(guò)setShape(int shape) 方法來(lái)進(jìn)行設(shè)置,這里一共可以設(shè)置四種形狀:
- GradientDrawable.RECTANGLE:矩形
- GradientDrawable.OVAL:橢圓形
- GradientDrawable.LINE:一條線
- GradientDrawable.RING:環(huán)形(環(huán)形試了好久不知為何畫不出來(lái))
這里用GradientDrawable.OVAL來(lái)實(shí)驗(yàn)一下:
GradientDrawable background = new GradientDrawable();
background.setColor(Color.GREEN);
background.setShape(GradientDrawable.OVAL);
view.setBackgroundDrawable(background);

如果想讓效果更加豐富一些添加描邊或者顏色漸變:
GradientDrawable background = new GradientDrawable();
background.setShape(GradientDrawable.OVAL);
background.setStroke(10,Color.RED);//設(shè)置寬度為10px的紅色描邊
background.setGradientType(GradientDrawable.LINEAR_GRADIENT);//設(shè)置線性漸變,除此之外還有:GradientDrawable.SWEEP_GRADIENT(掃描式漸變),GradientDrawable.RADIAL_GRADIENT(圓形漸變)
background.setColors(new int[]{Color.RED,Color.BLUE});//增加漸變效果需要使用setColors方法來(lái)設(shè)置顏色(中間可以增加多個(gè)顏色值)
view.setBackgroundDrawable(background);
