Android打造萬能自定義陰影控件

目錄介紹

  • 01.陰影效果有哪些實現方式
  • 02.實現陰影效果Api
  • 03.設置陰影需要注意哪些
  • 04.常見Shape實現陰影效果
  • 05.自定義陰影效果控件
  • 06.如何使用該陰影控件
  • 07.在recyclerView中使用注意點

01.陰影效果有哪些實現方式

  • 陰影效果有哪些實現方式

    • 第一種:使用CardView,但是不能設置陰影顏色
    • 第二種:採用shape疊加,存在後期UI效果不便優化
    • 第三種:UI切圖
    • 第四種:自定義View
  • 否定上面前兩種方案原因分析?

    • 第一個方案的CardView漸變色和陰影效果很難控制,只能支持線性或者環裝形式漸變,這種不滿足需要,因爲陰影本身是一個四周一層很淡的顏色包圍,在一個矩形框的層面上顏色大概一致,而且這個CardView有很多侷限性,比如不能修改陰影的顏色,不能修改陰影的深淺。所以這個思路無法實現這個需求。
    • 第二個採用shape疊加,可以實現陰影效果,但是影響UI,且陰影部分是佔像素的,而且不靈活。
    • 第三個方案詢問了一下ui。他們給出的結果是如果使用切圖的話那標註的話很難標,身爲一個優秀的設計師大多對像素點都和敏感,界面上的像素點有一點不協調那都是無法容忍的。
    • 在下面開源案例代碼中,我會一一展示這幾種不同方案實現的陰影效果。
  • 網上一些介紹陰影效果方案

    • 所有在深奧的技術,也都是爲需求做準備的。也就是需要實踐並且可以用到實際開發中,這篇文章不再抽象介紹陰影效果原理,理解三維空間中如何處理偏移光線達到陰影視差等,網上看了一些文章也沒看明白或者理解。這篇博客直接通過調用api實現預期的效果。
  • 陰影是否佔位

    • 使用CardView陰影不佔位,不能設置陰影顏色和效果
    • 使用shape陰影是可以設置陰影顏色,但是是佔位的

02.實現陰影效果Api

  • 思考一下如何實現View陰影效果?

    • 首先要明確陰影的實現思路是什麼,其實就是顏色導致的視覺錯覺。說白了就是在你的Card周圍畫一個漸變的體現立體感的顏色。基於上述思路,我們在一個在一個view上畫一個矩形的圖形,讓他周圍有漸變色的陰影即可。於是我們想起幾個API:
    • 類:Paint 用於在Android上畫圖的類,相當於畫筆
    • 類:Canvas 相當於畫布,Android上的view的繪製都與他相關
    • 方法:paint.setShadowLayer可以給繪製的圖形增加陰影,還可以設置陰影的顏色
  • paint.setShadowLayer(float radius, float dx, float dy, int shadowColor);

    • 這個方法可以達到這樣一個效果,在使用canvas畫圖時給視圖順帶上一層陰影效果。
  • 簡單介紹一下這幾個參數:

    • radius: 陰影半徑,主要可以控制陰影的模糊效果以及陰影擴散出去的大小。
    • dx:陰影在X軸方向上的偏移量
    • dy: 陰影在Y軸方向上的偏移量
    • shadowColor: 陰影顏色。
  • 終於找到了設置顏色的,通過設置shadowColor來控制視圖的陰影顏色。

03.設置陰影需要注意哪些

  • 其中涉及到幾個屬性,陰影的寬度,view到Viewgroup的距離,如果視圖和父佈局一樣大的話,那陰影就不好顯示,如果要能夠顯示出來就必須設置clipChildren=false。
  • 還有就是視圖自帶的圓角,大部分背景都是有圓角的,比如上圖中的圓角,需要達到高度還原陰影的效果就是的陰影的圓角和背景保持一致。

04.常見Shape實現陰影效果

  • 多個drawable疊加

    • 使用layer-list可以將多個drawable按照順序層疊在一起顯示,默認情況下,所有的item中的drawable都會自動根據它附上view的大小而進行縮放,layer-list中的item是按照順序從下往上疊加的,即先定義的item在下面,後面的依次往上面疊放
  • 陰影效果代碼如下所示

    • 這裏有多層,就省略了一些。然後直接通過設置控件的background屬性即可實現。
    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <shape android:shape="rectangle">
                <solid android:color="@color/indexShadowColor_1" />
                <corners android:radius="5dip" />
                <padding
                    android:bottom="1dp"
                    android:left="1dp"
                    android:right="1dp"
                    android:top="1dp" />
            </shape>
        </item>
        <item>
            <shape android:shape="rectangle">
                <solid android:color="@color/indexShadowColor_2" />
                <corners android:radius="5dip" />
                <padding
                    android:bottom="1dp"
                    android:left="1dp"
                    android:right="1dp"
                    android:top="1dp" />
            </shape>
        </item>
        
        ……
    
        <item>
            <shape android:shape="rectangle">
                <corners android:radius="5dip" />
                <solid android:color="@color/indexColor" />
            </shape>
        </item>
    </layer-list>

05.自定義陰影效果控件

  • 首先自定義屬性

    <declare-styleable name="ShadowLayout">
        <!--陰影的圓角大小-->
        <attr name="yc_cornerRadius" format="dimension" />
        <!--陰影的擴散範圍(也可以理解爲擴散程度)-->
        <attr name="yc_shadowLimit" format="dimension" />
        <!--陰影顏色-->
        <attr name="yc_shadowColor" format="color" />
        <!--x軸的偏移量-->
        <attr name="yc_dx" format="dimension" />
        <!--y軸的偏移量-->
        <attr name="yc_dy" format="dimension" />
        <!--左邊是否顯示陰影-->
        <attr name="yc_leftShow" format="boolean" />
        <!--右邊是否顯示陰影-->
        <attr name="yc_rightShow" format="boolean" />
        <!--上邊是否顯示陰影-->
        <attr name="yc_topShow" format="boolean" />
        <!--下面是否顯示陰影-->
        <attr name="yc_bottomShow" format="boolean" />
    </declare-styleable>
  • 代碼如下所示

    /**
     * <pre>
     *     @author yangchong
     *     blog  : https://github.com/yangchong211
     *     time  : 2018/7/20
     *     desc  : 自定義陰影
     *     revise:
     * </pre>
     */
    public class ShadowLayout extends FrameLayout {
    
        /**
         * 陰影顏色
         */
        private int mShadowColor;
        /**
         * 陰影的擴散範圍(也可以理解爲擴散程度)
         */
        private float mShadowLimit;
        /**
         * 陰影的圓角大小
         */
        private float mCornerRadius;
        /**
         * x軸的偏移量
         */
        private float mDx;
        /**
         * y軸的偏移量
         */
        private float mDy;
        /**
         * 左邊是否顯示陰影
         */
        private boolean leftShow;
        /**
         * 右邊是否顯示陰影
         */
        private boolean rightShow;
        /**
         * 上邊是否顯示陰影
         */
        private boolean topShow;
        /**
         * 下面是否顯示陰影
         */
        private boolean bottomShow;
    
    
        private boolean mInvalidateShadowOnSizeChanged = true;
        private boolean mForceInvalidateShadow = false;
    
        public ShadowLayout(Context context) {
            super(context);
            initView(context, null);
        }
    
        public ShadowLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
            initView(context, attrs);
        }
    
        public ShadowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initView(context, attrs);
        }
    
        @Override
        protected int getSuggestedMinimumWidth() {
            return 0;
        }
    
        @Override
        protected int getSuggestedMinimumHeight() {
            return 0;
        }
    
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            if (w > 0 && h > 0 && (getBackground() == null || mInvalidateShadowOnSizeChanged
                    || mForceInvalidateShadow)) {
                mForceInvalidateShadow = false;
                setBackgroundCompat(w, h);
            }
        }
    
        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            if (mForceInvalidateShadow) {
                mForceInvalidateShadow = false;
                setBackgroundCompat(right - left, bottom - top);
            }
        }
    
        public void setInvalidateShadowOnSizeChanged(boolean invalidateShadowOnSizeChanged) {
            mInvalidateShadowOnSizeChanged = invalidateShadowOnSizeChanged;
        }
    
        public void invalidateShadow() {
            mForceInvalidateShadow = true;
            requestLayout();
            invalidate();
        }
    
        private void initView(Context context, AttributeSet attrs) {
            initAttributes(context, attrs);
    
            int xPadding = (int) (mShadowLimit + Math.abs(mDx));
            int yPadding = (int) (mShadowLimit + Math.abs(mDy));
            int left;
            int right;
            int top;
            int bottom;
            if (leftShow) {
                left = xPadding;
            } else {
                left = 0;
            }
    
            if (topShow) {
                top = yPadding;
            } else {
                top = 0;
            }
    
    
            if (rightShow) {
                right = xPadding;
            } else {
                right = 0;
            }
    
            if (bottomShow) {
                bottom = yPadding;
            } else {
                bottom = 0;
            }
    
            setPadding(left, top, right, bottom);
        }
    
        @SuppressWarnings("deprecation")
        private void setBackgroundCompat(int w, int h) {
            Bitmap bitmap = createShadowBitmap(w, h, mCornerRadius, mShadowLimit, mDx,
                    mDy, mShadowColor, Color.TRANSPARENT);
            BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
                setBackgroundDrawable(drawable);
            } else {
                setBackground(drawable);
            }
        }
    
    
        private void initAttributes(Context context, AttributeSet attrs) {
            TypedArray attr = getTypedArray(context, attrs, R.styleable.ShadowLayout);
            if (attr == null) {
                return;
            }
    
            try {
                //默認是顯示
                leftShow = attr.getBoolean(R.styleable.ShadowLayout_yc_leftShow, true);
                rightShow = attr.getBoolean(R.styleable.ShadowLayout_yc_rightShow, true);
                bottomShow = attr.getBoolean(R.styleable.ShadowLayout_yc_bottomShow, true);
                topShow = attr.getBoolean(R.styleable.ShadowLayout_yc_topShow, true);
    
                mCornerRadius = attr.getDimension(R.styleable.ShadowLayout_yc_cornerRadius, 0);
                mShadowLimit = attr.getDimension(R.styleable.ShadowLayout_yc_shadowLimit, 0);
                mDx = attr.getDimension(R.styleable.ShadowLayout_yc_dx, 0);
                mDy = attr.getDimension(R.styleable.ShadowLayout_yc_dy, 0);
                mShadowColor = attr.getColor(R.styleable.ShadowLayout_yc_shadowColor,
                        getResources().getColor(R.color.default_shadow_color));
            } finally {
                attr.recycle();
            }
        }
    
        private TypedArray getTypedArray(Context context, AttributeSet attributeSet, int[] attr) {
            return context.obtainStyledAttributes(attributeSet, attr, 0, 0);
        }
    
        private Bitmap createShadowBitmap(int shadowWidth, int shadowHeight, float cornerRadius,
                                          float shadowRadius, float dx, float dy,
                                          int shadowColor, int fillColor) {
    
            //根據寬高創建bitmap背景
            Bitmap output = Bitmap.createBitmap(shadowWidth, shadowHeight, Bitmap.Config.ARGB_8888);
            //用畫板canvas進行繪製
            Canvas canvas = new Canvas(output);
            RectF shadowRect = new RectF(shadowRadius, shadowRadius,
                    shadowWidth - shadowRadius, shadowHeight - shadowRadius);
    
            if (dy > 0) {
                shadowRect.top += dy;
                shadowRect.bottom -= dy;
            } else if (dy < 0) {
                shadowRect.top += Math.abs(dy);
                shadowRect.bottom -= Math.abs(dy);
            }
    
            if (dx > 0) {
                shadowRect.left += dx;
                shadowRect.right -= dx;
            } else if (dx < 0) {
                shadowRect.left += Math.abs(dx);
                shadowRect.right -= Math.abs(dx);
            }
    
            Paint shadowPaint = new Paint();
            shadowPaint.setAntiAlias(true);
            shadowPaint.setColor(fillColor);
            shadowPaint.setStyle(Paint.Style.FILL);
            if (!isInEditMode()) {
                shadowPaint.setShadowLayer(shadowRadius, dx, dy, shadowColor);
            }
            canvas.drawRoundRect(shadowRect, cornerRadius, cornerRadius, shadowPaint);
            return output;
        }
    }

06.如何使用該陰影控件

  • 十分簡單,如下所示

    <com.ns.yc.yccardviewlib.shadow.ShadowLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        app:yc_cornerRadius="18dp"
        app:yc_dx="0dp"
        app:yc_dy="0dp"
        app:yc_shadowColor="#2a000000"
        app:yc_shadowLimit="5dp">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="36dp"
            android:background="@drawable/shape_show_"
            android:gravity="center"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="完全圓形圓角"
            android:textColor="#000" />
    
    </com.ns.yc.yccardviewlib.shadow.ShadowLayout>

07.在recyclerView中使用注意點

  • 在createShadowBitmap方法中,其實也可以看到需要創建bitmap對象。大家都知道bitmap比較容易造成內存過大,如果是給recyclerView中的item設置陰影效果,那麼如何避免重複創建,這時候可以用到緩存。所以可以在上面的基礎上再優化一下代碼。
  • 先創建key,主要是用於map集合的鍵。這裏爲何用對象Key作爲map的鍵呢,這裏是借鑑了glide緩存圖片的思路,可以創建Key對象的時候傳入bitmap名稱和寬高屬性,並且需要重寫hashCode和equals方法。

    public class Key {
    
        private final String name;
        private final int width;
        private final int height;
    
        public Key(String name, int width, int height) {
            this.name = name;
            this.width = width;
            this.height = height;
        }
    
        public String getName() {
            return name;
        }
    
        public int getWidth() {
            return width;
        }
    
        public int getHeight() {
            return height;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            Key key = (Key) o;
            if (width != key.width) {
                return false;
            }
            if (height != key.height) {
                return false;
            }
            return name != null ? name.equals(key.name) : key.name == null;
        }
    
        @Override
        public int hashCode() {
            int result = name != null ? name.hashCode() : 0;
            result = 31 * result + width;
            result = 31 * result + height;
            return result;
        }
    }
  • 然後存取操作如下所示

    • 在查找的時候,通過Key進行查找。注意:Bitmap需要同時滿足三個條件(高度、寬度、名稱)都相同時才能算是同一個 Bitmap。
    Key key = new Key("bitmap", shadowWidth, shadowHeight);
    Bitmap output = cache.get(key);
    if(output == null){
        //根據寬高創建bitmap背景
        output = Bitmap.createBitmap(shadowWidth, shadowHeight, Bitmap.Config.ARGB_8888);
        cache.put(key, output);
        LogUtil.v("bitmap對象-----","----直接創建對象,然後存入緩存之中---");
    } else {
        LogUtil.v("bitmap對象-----","----從緩存中取出對象---");
    }

其他介紹

01.關於博客彙總鏈接

02.關於我的博客

開源案例地址:https://github.com/yangchong211/YCCardView

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章