Android開發 ShapeDrawable詳解


前言

  ShapeDrawable一開始我以為它是對應xml文件屬性里的shape的畫圖,后來發現我錯了... 其實ShapeDrawable更像是一共自由度更大跟偏向與實現draw()方法的一共圖像繪制類.所以,它的優點就是可以有更大的自由在代碼里繪制一個你想要的圖形,缺點是它搞起來有點不太方便,對於只需要簡單的圖形還不如GradientDrawable方便.

  ShapeDrawable是靠new一個繼承Shape的類,來實現方便你的繪制的(其實底層原理就是View的draw()那套東西).我們可以查到一共有多少個shape,看如下圖片:

  

畫圓形 OvalShape

        ShapeDrawable shapeDrawable = new ShapeDrawable(new OvalShape());
        shapeDrawable.getPaint().setColor(Color.BLACK);
        Rect rect = new Rect();
        rect.top = 0;
        rect.left = 0;
        rect.bottom = 50;
        rect.right = 50;
        shapeDrawable.setBounds(rect);
        mTextView.setBackground(shapeDrawable);

效果圖:

 

畫半圓 ArcShape

        ShapeDrawable shapeDrawable = new ShapeDrawable(new ArcShape(0,180));//ArcShape參數 開始角度startAngle 要畫多少角度sweepAngle
        shapeDrawable.getPaint().setColor(Color.BLACK);
        Rect rect = new Rect();
        rect.top = 0;
        rect.left = 0;
        rect.bottom = 50;
        rect.right = 50;
        shapeDrawable.setBounds(rect);
        mTextView.setBackground(shapeDrawable);

效果圖:

畫矩形 RectShape

        ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
        shapeDrawable.getPaint().setColor(Color.BLACK);
        Rect rect = new Rect();
        rect.top = 0;
        rect.left = 0;
        rect.bottom = 50;
        rect.right = 50;
        shapeDrawable.setBounds(rect);
        mTextView.setBackground(shapeDrawable);

效果圖:

畫內外雙層矩形,並且有圓角 RoundRectShape

        float[] externalRound = {8, 8, 8, 8, 8, 8, 8, 8};//外部矩形的8個圓角半徑,為什么是8個? 因為這個居然是一個角2個半圓組成的(太精細了...)
        RectF distanceRectF = new RectF(10, 10, 10, 10); //內部矩形與外部矩形的距離
        float[] insideRound = {10, 10, 10, 10, 10, 10, 10, 10}; //內部矩形的8個圓角半徑值
        ShapeDrawable shapeDrawable = new ShapeDrawable(new RoundRectShape(externalRound, distanceRectF, insideRound));
        shapeDrawable.getPaint().setColor(Color.BLACK);
        Rect rect = new Rect();
        rect.top = 0;
        rect.left = 0;
        rect.bottom = 50;
        rect.right = 50;
        shapeDrawable.setBounds(rect);
        mTextView.setBackground(shapeDrawable);

public RoundRectShape(@Nullable float[] outerRadii, @Nullable RectF inset, @Nullable float[] innerRadii)  這個類一共有3個參數,我在上面的注解已經說明了.

注意!這3個參數都是可以為null的.意思就是,你可以取消任意一個.獲得一些其他效果,比如設置第二個和第三個參數為null,你就可以得到一個實心的圓角矩形.

效果圖:

 

畫任意形狀 PathShape

  待續....


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM