Android Android中的13種Drawable小結(jié) Part 1

2023-03-31 14:17 更新

本節(jié)引言:

從本節(jié)開(kāi)始我們來(lái)學(xué)習(xí)Android中繪圖與動(dòng)畫(huà)中的一些基礎(chǔ)知識(shí),為我們進(jìn)階部分的自定義 打下基礎(chǔ)!而第一節(jié)我們來(lái)扣下Android中的Drawable!Android中給我們提供了多達(dá)13種的 Drawable,本節(jié)我們就來(lái)一個(gè)個(gè)擼一遍!


Drawable資源使用注意事項(xiàng)

  • Drawable分為兩種: 一種是我們普通的圖片資源,在Android Studio中我們一般放到res/mipmap目錄下, 和以前的Eclipse不一樣哦!另外我們?nèi)绻压こ糖袚Q成Android項(xiàng)目模式,我們直接 往mipmap目錄下丟圖片即可,AS會(huì)自動(dòng)分hdpi,xhdpi...! 另一種是我們編寫(xiě)的XML形式的Drawable資源,我們一般把他們放到res/drawable目錄 下,比如最常見(jiàn)的按鈕點(diǎn)擊背景切換的Selctor!
  • 在XML我們直接通過(guò)@mipmap或者@drawable設(shè)置Drawable即可 比如: android:background = "@mipmap/iv_icon_zhu" / "@drawable/btn_back_selctor" 而在Java代碼中我們可以通過(guò)Resource的getDrawable(R.mipmap.xxx)可以獲得drawable資源 如果是為某個(gè)控件設(shè)置背景,比如ImageView,我們可以直接調(diào)用控件.getDrawale()同樣 可以獲得drawable對(duì)象!
  • Android中drawable中的資源名稱有約束,必須是:[a-z0-9_.](即:只能是字母數(shù)字及和.), 而且不能以數(shù)字開(kāi)頭,否則編譯會(huì)報(bào)錯(cuò): Invalid file name: must contain only [a-z0-9.]! 小寫(xiě)啊?。。?!小寫(xiě)!??!小寫(xiě)!——重要事情說(shuō)三遍~

好的,要注意的地方大概就這些,下面我們來(lái)對(duì)Android中給我們提供的13種Drawable進(jìn)行學(xué)習(xí)!


1.ColorDrawable

最簡(jiǎn)單的一種Drawable,當(dāng)我們將ColorDrawable繪制到Canvas(畫(huà)布)上的時(shí)候, 會(huì)使用一種固定的顏色來(lái)填充Paint,然后在畫(huà)布上繪制出一片單色區(qū)域!

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"/>  

當(dāng)然上面這些用法,其實(shí)用得不多,更多的時(shí)候我們是在res/values目錄下創(chuàng)建一個(gè)color.xml 文件,然后把要用到的顏色值寫(xiě)到里面,需要的時(shí)候通過(guò)@color獲得相應(yīng)的值,比如:

3).建立一個(gè)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文件中話我們可以通過(guò)@color/xxx獲得對(duì)應(yīng)的color值 如果是在Java中:

int mycolor = getResources().getColor(R.color.mycolor);    
btn.setBackgroundColor(mycolor);  

ps:另外有一點(diǎn)要注意,如果我們?cè)贘ava中直接定義顏色值的話,要加上0x,而且不能把透明度漏掉:

int mycolor = 0xff123456;    
btn.setBackgroundColor(mycolor); 

4).使用系統(tǒng)定義好的color:

比如:BLACK(黑色),BLUE(藍(lán)色),CYAN(青色),GRAY(灰色),GREEN(綠色),RED(紅色),WRITE(白色),YELLOW(黃色)! 用法: btn.setBackgroundColor(Color.BLUE); 也可以獲得系統(tǒng)顏色再設(shè)置:

int getcolor = Resources.getSystem().getColor(android.R.color.holo_green_light);  
btn.setBackgroundColor(getcolor);  

xml中使用:android:background="@android:color/black"

5).利用靜態(tài)方法argb來(lái)設(shè)置顏色:

Android使用一個(gè)int類型的數(shù)據(jù)表示顏色值,通常是十六進(jìn)制,即0x開(kāi)頭, 顏色值的定義是由透明度alpha和RGB(紅綠藍(lán))三原色來(lái)定義的,以"#"開(kāi)始,后面依次為: 
透明度-紅-綠-藍(lán);eg:#RGB #ARGB #RRGGBB #AARRGGBB 
每個(gè)要素都由一個(gè)字節(jié)(8 bit)來(lái)表示,所以取值范圍為0~255,在xml中設(shè)置顏色可以忽略透明度, 但是如果你是在Java代碼中的話就需要明確指出透明度的值了,省略的話表示完全透明,這個(gè)時(shí)候 就沒(méi)有效果了哦~比如:0xFF0000雖然表示紅色,但是如果直接這樣寫(xiě),什么的沒(méi)有,而應(yīng)該這樣寫(xiě): 0xFFFF0000,記Java代碼設(shè)置顏色值,需要在前面添加上透明度~ 示例:(參數(shù)依次為:透明度,紅色值,綠色值,藍(lán)色值)txtShow.setBackgroundColor(Color.argb(0xff, 0x00, 0x00, 0x00));


2.NiewPatchDrawable

就是.9圖咯,在前面我們1.6 .9(九妹)圖片怎么玩已經(jīng)詳細(xì) 的給大家講解了一下如何制作.9圖片了!Android FrameWork在顯示點(diǎn)九圖時(shí)使用了高效的 圖形優(yōu)化算法,我們不需要特殊的處理,就可以實(shí)現(xiàn)圖片拉伸的自適應(yīng)~ 另外在使用AS的時(shí)候要注意以下幾點(diǎn):

  • 1.點(diǎn)9圖不能放在mipmap目錄下,而需要放在drawable目錄下!
  • 2.AS中的.9圖,必須要有黑線,不然編譯都不會(huì)通過(guò),今早我的阿君表哥在群里說(shuō) 他司的美工給了他一個(gè)沒(méi)有黑線的.9圖,說(shuō)使用某軟件制作出來(lái)的,然后在Eclipse上 是可以用的,沒(méi)錯(cuò)是沒(méi)黑線的.9,臥槽,然而我換到AS上,直接編譯就不通過(guò)了! 感覺(jué)是AS識(shí)別.9圖的其中標(biāo)準(zhǔn)是需要有黑店或者黑線!另外表哥給出的一個(gè)去掉黑線的: 9patch(.9)怎么去掉自己畫(huà)上的黑點(diǎn)/黑線 具體我沒(méi)試,有興趣可以自己試試,但是黑線真的那么礙眼么...我沒(méi)強(qiáng)迫癥不覺(jué)得! 另外還有一點(diǎn)就是解壓別人apk,拿.9素材的時(shí)候發(fā)現(xiàn)并沒(méi)有黑線,同樣也會(huì)報(bào)錯(cuò)! 想要拿出有黑線的.9素材的話,需要反編譯apk而非直接解壓!??!反編譯前面也 介紹過(guò)了,這里就不詳述了!

接著介紹兩個(gè)沒(méi)什么卵用的東東:

xml定義NinePatchDrawable:

<!--pic9.xml-->  
<!--參數(shù)依次為:引用的.9圖片,是否對(duì)位圖進(jìn)行抖動(dòng)處理-->  
<?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-->  
<!--參數(shù)依次為:引用的.9圖片,是否對(duì)位圖進(jìn)行抖動(dòng)處理-->  
<?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咯,定義基本的幾何圖形,如(矩形,圓形,線條等),根元素是 節(jié)點(diǎn)比較多,相關(guān)的節(jié)點(diǎn)如下:

  • ① :
  • visible:設(shè)置是否可見(jiàn)
  • shape:形狀,可選:rectangle(矩形,包括正方形),oval(橢圓,包括圓),line(線段),ring(環(huán)形)
  • innerRadiusRatio:當(dāng)shape為ring才有效,表示環(huán)內(nèi)半徑所占半徑的比率,如果設(shè)置了innerRadius, 他會(huì)被忽略
  • innerRadius:當(dāng)shape為ring才有效,表示環(huán)的內(nèi)半徑的尺寸
  • thicknessRatio:當(dāng)shape為ring才有效,表環(huán)厚度占半徑的比率
  • thickness:當(dāng)shape為ring才有效,表示環(huán)的厚度,即外半徑與內(nèi)半徑的差
  • useLevel:當(dāng)shape為ring才有效,表示是否允許根據(jù)level來(lái)顯示環(huán)的一部分
  • ②:
  • width:圖形形狀寬度
  • height:圖形形狀高度
  • ③:后面GradientDrawable再講~
  • color:背景填充色,設(shè)置solid后會(huì)覆蓋gradient設(shè)置的所有效果!!!!!!
  • width:邊框的寬度
  • color:邊框的顏色
  • dashWidth:邊框虛線段的長(zhǎng)度
  • dashGap:邊框的虛線段的間距
  • radius:圓角半徑,適用于上下左右四個(gè)角
  • topLeftRadius,topRightRadius,BottomLeftRadius,tBottomRightRadius: 依次是左上,右上,左下,右下的圓角值,按自己需要設(shè)置!
  • left,top,right,bottm:依次是左上右下方向上的邊距!

使用示例: 2.3.1 TextView(文本框)詳解


4.GradientDrawable

一個(gè)具有漸變區(qū)域的Drawable,可以實(shí)現(xiàn)線性漸變,發(fā)散漸變和平鋪漸變效果 核心節(jié)點(diǎn):,有如下可選屬性:

  • startColor:漸變的起始顏色
  • centerColor:漸變的中間顏色
  • endColor:漸變的結(jié)束顏色
  • type:漸變類型,可選(linear,radial,sweep), 線性漸變(可設(shè)置漸變角度),發(fā)散漸變(中間向四周發(fā)散),平鋪漸變
  • centerX:漸變中間亞瑟的x坐標(biāo),取值范圍為:0~1
  • centerY:漸變中間顏色的Y坐標(biāo),取值范圍為:0~1
  • angle:只有l(wèi)inear類型的漸變才有效,表示漸變角度,必須為45的倍數(shù)哦
  • gradientRadius:只有radial和sweep類型的漸變才有效,radial必須設(shè)置,表示漸變效果的半徑
  • useLevel:判斷是否根據(jù)level繪制漸變效果

代碼示例:(三種漸變效果的演示):

運(yùn)行效果圖

先在drawable下創(chuàng)建三個(gè)漸變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>

(發(fā)散漸變)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> 

調(diào)用三個(gè)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>  

好的,就是那么簡(jiǎn)單~當(dāng)然,如果想繪制更加復(fù)雜的圖形的話,只用xml文件不遠(yuǎn)遠(yuǎn)不足的, 更復(fù)雜的效果則需要通過(guò)Java代碼來(lái)完成,下面演示的是摘自網(wǎng)上的一個(gè)源碼:

運(yùn)行效果圖:

實(shí)現(xiàn)代碼

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,前者是對(duì)普通圖形的包裝;包括: ArcShape,OvalShape,PathShape,RectShape,RoundRectShape!
而PathEffect則是路徑特效,包括:CornerPathEffect,DashPathEffect和DiscretePathEffect 可以制作復(fù)雜的圖形邊框...
關(guān)于這個(gè)GradoemtDrawable漸變就講到這里,如果你對(duì)最后面這個(gè)玩意有興趣的話,可以到: appium/android-apidemos


本節(jié)小結(jié):

 好的,本節(jié)就先學(xué)習(xí)ColorDrawable,NiewPatchDrawable,ShapeDrawable,GradientDrawable
四個(gè)Drawable先,當(dāng)然這些都是炒冷飯,以前已經(jīng)寫(xiě)過(guò)了,不過(guò)為了教程的完整性,還是決定 在寫(xiě)一遍~另外,在寫(xiě)完基礎(chǔ)教程后,以前寫(xiě)過(guò)的一些blog會(huì)刪掉!

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)