Android中的13種Drawable小結
Android中給我們提供了多達13種的 Drawable,本節我們就來一個個擼一遍!
Drawable資源使用注意事項
- Drawable分為兩種: 一種是我們普通的圖片資源,在Android Studio中我們一般放到res/mipmap目錄下, 和以前的Eclipse不一樣哦!另外我們如果把工程切換成Android專案模式,我們直接 往mipmap目錄下丟圖片即可,AS會自動分hdpi,xhdpi...! 另一種是我們編寫的XML形式的Drawable資源,我們一般把他們放到res/drawable目錄 下,比如最常見的按鈕點選背景切換的Selctor!
- 在XML我們直接通過@mipmap或者@drawable設定Drawable即可 比如: android:background = "@mipmap/iv_icon_zhu" / "@drawable/btn_back_selctor" 而在Java程式碼中我們可以通過Resource的getDrawable(
R.mipmap.xxx)可以獲得drawable資源 如果是為某個控制元件設定背景,比如ImageView,我們可以直接呼叫控制元件.getDrawale()同樣 可以獲得drawable物件!- Android中drawable中的資源名稱有約束,必須是:[a-z0-9_.](即:只能是字母數字及和.), 而且不能以數字開頭,否則編譯會報錯: Invalid file name: must contain only [a-z0-9.]! 小寫啊!!!!小寫!!!小寫!——重要事情說三遍~
好的,要注意的地方大概就這些,下面我們來對Android中給我們提供的13種Drawable進行學習!
1.ColorDrawable
最簡單的一種Drawable,當我們將ColorDrawable繪製到Canvas(畫布)上的時候, 會使用一種固定的顏色來填充Paint,然後在畫布上繪製出一片單色區域!
1).Java中定義ColorDrawable:
ColorDrawable drawable = new ColorDrawable(0xffff2200);
txtShow.setBackground(drawable);
2).在xml中定義ColorDrawable:
<?xml version="1.0" encoding="utf-8"?> <color xmlns:android="http://schemas.android.com/apk/res/android" android:color="#FF0000"/>
當然上面這些用法,其實用得不多,更多的時候我們是在res/values目錄下建立一個color.xml 檔案,然後把要用到的顏色值寫到裡面,需要的時候通過@color獲得相應的值,比如:
3).建立一個color.xml檔案
比如:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="material_grey_100">#fff5f5f5</color>
<color name="material_grey_300">#ffe0e0e0</color>
<color name="material_grey_50">#fffafafa</color>
<color name="material_grey_600">#ff757575</color>
<color name="material_grey_800">#ff424242</color>
<color name="material_grey_850">#ff303030</color>
<color name="material_grey_900">#ff212121</color>
</resources>
然後如果是在xml檔案中話我們可以通過@color/xxx獲得對應的color值 如果是在Java中:
int mycolor = getResources().getColor(R.color.mycolor);
btn.setBackgroundColor(mycolor);
ps:另外有一點要注意,如果我們在Java中直接定義顏色值的話,要加上0x,而且不能把透明度漏掉:
int mycolor = 0xff123456;
btn.setBackgroundColor(mycolor);
4).使用系統定義好的color:
比如:BLACK(黑色),BLUE(藍色),CYAN(青色),GRAY(灰色),GREEN(綠色),RED(紅色),WRITE(白色),YELLOW(黃色)! 用法: btn.setBackgroundColor(Color.BLUE); 也可以獲得系統顏色再設定:
int getcolor = Resources.getSystem().getColor(android.R.color.holo_green_light);
btn.setBackgroundColor(getcolor);
xml中使用:android:background="@android:color/black"
5).利用靜態方法argb來設定顏色:
Android使用一個int型別的資料表示顏色值,通常是十六進位制,即0x開頭, 顏色值的定義是由透明度alpha和RGB(紅綠藍)三原色來定義的,以"#"開始,後面依次為: 透明度-紅-綠-藍;eg:#RGB #ARGB #RRGGBB #AARRGGBB 每個要素都由一個位元組(8 bit)來表示,所以取值範圍為0~255,在xml中設定顏色可以忽略透明度, 但是如果你是在Java程式碼中的話就需要明確指出透明度的值了,省略的話表示完全透明,這個時候 就沒有效果了哦~比如:0xFF0000雖然表示紅色,但是如果直接這樣寫,什麼的沒有,而應該這樣寫: 0xFFFF0000,記Java程式碼設定顏色值,需要在前面新增上透明度~ 示例:(引數依次為:透明度,紅色值,綠色值,藍色值)txtShow.setBackgroundColor(Color.argb(0xff, 0x00, 0x00, 0x00));
2.NiewPatchDrawable
就是.9圖咯,在前面我們1.6 .9(九妹)圖片怎麼玩已經詳細 的給大家講解了一下如何製作.9圖片了!Android FrameWork在顯示點九圖時使用了高效的 圖形優化演算法,我們不需要特殊的處理,就可以實現圖片拉伸的自適應~ 另外在使用AS的時候要注意以下幾點:
- 1.點9圖不能放在mipmap目錄下,而需要放在drawable目錄下!
- 2.AS中的.9圖,必須要有黑線,不然編譯都不會通過,今早我的阿君表哥在群裡說 他司的美工給了他一個沒有黑線的.9圖,說使用某軟體製作出來的,然後在Eclipse上 是可以用的,沒錯是沒黑線的.9,臥槽,然而我換到AS上,直接編譯就不通過了! 感覺是AS識別.9圖的其中標準是需要有黑店或者黑線!另外表哥給出的一個去掉黑線的: 9patch(.9)怎麼去掉自己畫上的黑點/黑線 具體我沒試,有興趣可以自己試試,但是黑線真的那麼礙眼麼...我沒強迫症不覺得! 另外還有一點就是解壓別人apk,拿.9素材的時候發現並沒有黑線,同樣也會報錯! 想要拿出有黑線的.9素材的話,需要反編譯apk而非直接解壓!!!反編譯前面也 介紹過了,這裡就不詳述了!
接著介紹兩個沒什麼卵用的東東:
xml定義NinePatchDrawable:
<!--pic9.xml-->
<!--引數依次為:引用的.9圖片,是否對點陣圖進行抖動處理-->
<?xml version="1.0" encoding="utf-8"?>
<nine-patch
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/dule_pic"
android:dither="true"/>
使用Bitmap包裝.9圖片:
<!--pic9.xml-->
<!--引數依次為:引用的.9圖片,是否對點陣圖進行抖動處理-->
<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/dule_pic"
android:dither="true"/>
3.ShapeDrawable
形狀的Drawable咯,定義基本的幾何圖形,如(矩形,圓形,線條等),根元素是 節點比較多,相關的節點如下:
- ① :
- ~ visible:設定是否可見
- ~ shape:形狀,可選:rectangle(矩形,包括正方形),oval(橢圓,包括圓),line(線段),ring(環形)
- ~ innerRadiusRatio:當shape為ring才有效,表示環內半徑所佔半徑的比率,如果設定了innerRadius, 他會被忽略
- ~ innerRadius:當shape為ring才有效,表示環的內半徑的尺寸
- ~ thicknessRatio:當shape為ring才有效,表環厚度佔半徑的比率
- ~ thickness:當shape為ring才有效,表示環的厚度,即外半徑與內半徑的差
- ~ useLevel:當shape為ring才有效,表示是否允許根據level來顯示環的一部分
- ②:
- ~ width:圖形形狀寬度
- ~ height:圖形形狀高度
- ③:後面GradientDrawable再講~
- ④
- ~ color:背景填充色,設定solid後會覆蓋gradient設定的所有效果!!!!!!
- ⑤
- ~ width:邊框的寬度
- ~ color:邊框的顏色
- ~ dashWidth:邊框虛線段的長度
- ~ dashGap:邊框的虛線段的間距
- ⑥
- ~ radius:圓角半徑,適用於上下左右四個角
- ~ topLeftRadius,topRightRadius,BottomLeftRadius,tBottomRightRadius: 依次是左上,右上,左下,右下的圓角值,按自己需要設定!
- ⑦
- left,top,right,bottm:依次是左上右下方向上的邊距!
4.GradientDrawable
一個具有漸變區域的Drawable,可以實現線性漸變,發散漸變和平鋪漸變效果 核心節點:,有如下可選屬性:
- startColor:漸變的起始顏色
- centerColor:漸變的中間顏色
- endColor:漸變的結束顏色
- type:漸變型別,可選(linear,radial,sweep), 線性漸變(可設定漸變角度),發散漸變(中間向四周發散),平鋪漸變
- centerX:漸變中間亞瑟的x座標,取值範圍為:0~1
- centerY:漸變中間顏色的Y座標,取值範圍為:0~1
- angle:只有linear型別的漸變才有效,表示漸變角度,必須為45的倍數哦
- gradientRadius:只有radial和sweep型別的漸變才有效,radial必須設定,表示漸變效果的半徑
- useLevel:判斷是否根據level繪製漸變效果
程式碼示例:(三種漸變效果的演示):
執行效果圖:
先在drawable下建立三個漸變xml檔案:
(線性漸變)gradient_linear.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<gradient
android:angle="90"
android:centerColor="#FFEB82"
android:endColor="#35B2DE"
android:startColor="#DEACAB" />
<stroke
android:dashGap="5dip"
android:dashWidth="4dip"
android:width="3dip"
android:color="#fff" />
</shape>
(發散漸變)gradient_radial.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dip"
android:shape="ring"
android:thickness="70dip"
android:useLevel="false" >
<gradient
android:centerColor="#FFEB82"
android:endColor="#35B2DE"
android:gradientRadius="70"
android:startColor="#DEACAB"
android:type="radial"
android:useLevel="false" />
</shape>
(平鋪漸變)gradient_sweep.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadiusRatio="8"
android:shape="ring"
android:thicknessRatio="3"
android:useLevel="false" >
<gradient
android:centerColor="#FFEB82"
android:endColor="#35B2DE"
android:startColor="#DEACAB"
android:type="sweep"
android:useLevel="false" />
</shape>
呼叫三個drawable的activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/txtShow1"
android:layout_width="200dp"
android:layout_height="100dp"
android:background="@drawable/gradient_linear" />
<TextView
android:id="@+id/txtShow2"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@drawable/gradient_radial" />
<TextView
android:id="@+id/txtShow3"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/gradient_sweep" />
</LinearLayout>
好的,就是那麼簡單~當然,如果想繪製更加複雜的圖形的話,只用xml檔案不遠遠不足的, 更復雜的效果則需要通過Java程式碼來完成,下面演示的是摘自網上的一個原始碼:
執行效果圖:
實現程式碼:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private ShapeDrawable[] mDrawables;
private static Shader makeSweep() {
return new SweepGradient(150, 25,
new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFF0000 },
null);
}
private static Shader makeLinear() {
return new LinearGradient(0, 0, 50, 50,
new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF },
null, Shader.TileMode.MIRROR);
}
private static Shader makeTiling() {
int[] pixels = new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0};
Bitmap bm = Bitmap.createBitmap(pixels, 2, 2,
Bitmap.Config.ARGB_8888);
return new BitmapShader(bm, Shader.TileMode.REPEAT,
Shader.TileMode.REPEAT);
}
private static class MyShapeDrawable extends ShapeDrawable {
private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public MyShapeDrawable(Shape s) {
super(s);
mStrokePaint.setStyle(Paint.Style.STROKE);
}
public Paint getStrokePaint() {
return mStrokePaint;
}
@Override protected void onDraw(Shape s, Canvas c, Paint p) {
s.draw(c, p);
s.draw(c, mStrokePaint);
}
}
public SampleView(Context context) {
super(context);
setFocusable(true);
float[] outerR = new float[] { 12, 12, 12, 12, 0, 0, 0, 0 };
RectF inset = new RectF(6, 6, 6, 6);
float[] innerR = new float[] { 12, 12, 0, 0, 12, 12, 0, 0 };
Path path = new Path();
path.moveTo(50, 0);
path.lineTo(0, 50);
path.lineTo(50, 100);
path.lineTo(100, 50);
path.close();
mDrawables = new ShapeDrawable[7];
mDrawables[0] = new ShapeDrawable(new RectShape());
mDrawables[1] = new ShapeDrawable(new OvalShape());
mDrawables[2] = new ShapeDrawable(new RoundRectShape(outerR, null,
null));
mDrawables[3] = new ShapeDrawable(new RoundRectShape(outerR, inset,
null));
mDrawables[4] = new ShapeDrawable(new RoundRectShape(outerR, inset,
innerR));
mDrawables[5] = new ShapeDrawable(new PathShape(path, 100, 100));
mDrawables[6] = new MyShapeDrawable(new ArcShape(45, -270));
mDrawables[0].getPaint().setColor(0xFFFF0000);
mDrawables[1].getPaint().setColor(0xFF00FF00);
mDrawables[2].getPaint().setColor(0xFF0000FF);
mDrawables[3].getPaint().setShader(makeSweep());
mDrawables[4].getPaint().setShader(makeLinear());
mDrawables[5].getPaint().setShader(makeTiling());
mDrawables[6].getPaint().setColor(0x88FF8844);
PathEffect pe = new DiscretePathEffect(10, 4);
PathEffect pe2 = new CornerPathEffect(4);
mDrawables[3].getPaint().setPathEffect(
new ComposePathEffect(pe2, pe));
MyShapeDrawable msd = (MyShapeDrawable)mDrawables[6];
msd.getStrokePaint().setStrokeWidth(4);
}
@Override protected void onDraw(Canvas canvas) {
int x = 10;
int y = 10;
int width = 400;
int height = 100;
for (Drawable dr : mDrawables) {
dr.setBounds(x, y, x + width, y + height);
dr.draw(canvas);
y += height + 5;
}
}
}
}
程式碼使用了ShapeDrawable和PathEffect,前者是對普通圖形的包裝;包括: ArcShape,OvalShape,PathShape,RectShape,RoundRectShape! 而PathEffect則是路徑特效,包括:CornerPathEffect,DashPathEffect和DiscretePathEffect 可以製作複雜的圖形邊框..