您现在的位置是:首页 > 文章详情

Android打造万能自定义阴影控件

日期:2019-08-05点击:349

目录介绍

  • 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

原文链接:https://yq.aliyun.com/articles/712930
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章