当前位置:主页 > 移动开发 > Android代码 >

Android实现万能自定义阴影控件实例代码

时间:2020-11-24 16:52:01 | 栏目:Android代码 | 点击:

目录介绍

01.阴影效果有哪些实现方式

阴影效果有哪些实现方式

否定上面前两种方案原因分析?

网上一些介绍阴影效果方案

阴影是否占位

02.实现阴影效果Api

思考一下如何实现View阴影效果?

paint.setShadowLayer(float radius, float dx, float dy, int shadowColor);

简单介绍一下这几个参数:

终于找到了设置颜色的,通过设置shadowColor来控制视图的阴影颜色。

03.设置阴影需要注意哪些

其中涉及到几个属性,阴影的宽度,view到Viewgroup的距离,如果视图和父布局一样大的话,那阴影就不好显示,如果要能够显示出来就必须设置clipChildren=false。

还有就是视图自带的圆角,大部分背景都是有圆角的,比如上图中的圆角,需要达到高度还原阴影的效果就是的阴影的圆角和背景保持一致。

04.常见Shape实现阴影效果

多个drawable叠加

阴影效果代码如下所示

<?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:
 */
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 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对象-----","----从缓存中取出对象---");
}

总结

您可能感兴趣的文章:

相关文章