Android中怎么自定義一個(gè)陰影控件

Android中怎么自定義一個(gè)陰影控件,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

創(chuàng)新互聯(lián)主營(yíng)寶雞網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,APP應(yīng)用開(kāi)發(fā),寶雞h5小程序開(kāi)發(fā)搭建,寶雞網(wǎng)站營(yíng)銷推廣歡迎寶雞等地區(qū)企業(yè)咨詢

01.陰影效果有哪些實(shí)現(xiàn)方式

陰影效果有哪些實(shí)現(xiàn)方式

第一種:使用CardView,但是不能設(shè)置陰影顏色  第二種:采用shape疊加,存在后期UI效果不便優(yōu)化  第三種:UI切圖  第四種:自定義View

否定上面前兩種方案原因分析?

第一個(gè)方案的CardView漸變色和陰影效果很難控制,只能支持線性或者環(huán)裝形式漸變,這種不滿足需要,因?yàn)殛幱氨旧硎且粋€(gè)四周一層很淡的顏色包圍,在一個(gè)矩形框的層面上顏色大概一致,而且這個(gè)CardView有很多局限性,比如不能修改陰影的顏色,不能修改陰影的深淺。所以這個(gè)思路無(wú)法實(shí)現(xiàn)這個(gè)需求。  第二個(gè)采用shape疊加,可以實(shí)現(xiàn)陰影效果,但是影響UI,且陰影部分是占像素的,而且不靈活。  第三個(gè)方案詢問(wèn)了一下ui。他們給出的結(jié)果是如果使用切圖的話那標(biāo)注的話很難標(biāo),身為一個(gè)優(yōu)秀的設(shè)計(jì)師大多對(duì)像素點(diǎn)都和敏感,界面上的像素點(diǎn)有一點(diǎn)不協(xié)調(diào)那都是無(wú)法容忍的。  在下面開(kāi)源案例代碼中,我會(huì)一一展示這幾種不同方案實(shí)現(xiàn)的陰影效果。

網(wǎng)上一些介紹陰影效果方案

所有在深?yuàn)W的技術(shù),也都是為需求做準(zhǔn)備的。也就是需要實(shí)踐并且可以用到實(shí)際開(kāi)發(fā)中,這篇文章不再抽象介紹陰影效果原理,理解三維空間中如何處理偏移光線達(dá)到陰影視差等,網(wǎng)上看了一些文章也沒(méi)看明白或者理解。這篇博客直接通過(guò)調(diào)用api實(shí)現(xiàn)預(yù)期的效果。

陰影是否占位

使用CardView陰影不占位,不能設(shè)置陰影顏色和效果  使用shape陰影是可以設(shè)置陰影顏色,但是是占位的

02.實(shí)現(xiàn)陰影效果Api

思考一下如何實(shí)現(xiàn)View陰影效果?

首先要明確陰影的實(shí)現(xiàn)思路是什么,其實(shí)就是顏色導(dǎo)致的視覺(jué)錯(cuò)覺(jué)。說(shuō)白了就是在你的Card周圍畫一個(gè)漸變的體現(xiàn)立體感的顏色。基于上述思路,我們?cè)谝粋€(gè)在一個(gè)view上畫一個(gè)矩形的圖形,讓他周圍有漸變色的陰影即可。于是我們想起幾個(gè)API:  類:Paint 用于在Android上畫圖的類,相當(dāng)于畫筆  類:Canvas 相當(dāng)于畫布,Android上的view的繪制都與他相關(guān)  方法:paint.setShadowLayer可以給繪制的圖形增加陰影,還可以設(shè)置陰影的顏色

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

這個(gè)方法可以達(dá)到這樣一個(gè)效果,在使用canvas畫圖時(shí)給視圖順帶上一層陰影效果。

簡(jiǎn)單介紹一下這幾個(gè)參數(shù):

radius: 陰影半徑,主要可以控制陰影的模糊效果以及陰影擴(kuò)散出去的大小。  dx:陰影在X軸方向上的偏移量  dy: 陰影在Y軸方向上的偏移量  shadowColor: 陰影顏色。

終于找到了設(shè)置顏色的,通過(guò)設(shè)置shadowColor來(lái)控制視圖的陰影顏色。

03.設(shè)置陰影需要注意哪些

其中涉及到幾個(gè)屬性,陰影的寬度,view到Viewgroup的距離,如果視圖和父布局一樣大的話,那陰影就不好顯示,如果要能夠顯示出來(lái)就必須設(shè)置clipChildren=false。

還有就是視圖自帶的圓角,大部分背景都是有圓角的,比如上圖中的圓角,需要達(dá)到高度還原陰影的效果就是的陰影的圓角和背景保持一致。

04.常見(jiàn)Shape實(shí)現(xiàn)陰影效果

多個(gè)drawable疊加

使用layer-list可以將多個(gè)drawable按照順序?qū)盈B在一起顯示,默認(rèn)情況下,所有的item中的drawable都會(huì)自動(dòng)根據(jù)它附上view的大小而進(jìn)行縮放,layer-list中的item是按照順序從下往上疊加的,即先定義的item在下面,后面的依次往上面疊放

陰影效果代碼如下所示

這里有多層,就省略了一些。然后直接通過(guò)設(shè)置控件的background屬性即可實(shí)現(xiàn)。

<?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" />  <!--陰影的擴(kuò)散范圍(也可以理解為擴(kuò)散程度)-->  <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;  /**   * 陰影的擴(kuò)散范圍(也可以理解為擴(kuò)散程度)   */  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 {      //默認(rèn)是顯示      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) {    //根據(jù)寬高創(chuàng)建bitmap背景    Bitmap output = Bitmap.createBitmap(shadowWidth, shadowHeight, Bitmap.Config.ARGB_8888);    //用畫板canvas進(jìn)行繪制    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.如何使用該陰影控件

十分簡(jiǎn)單,如下所示

<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中使用注意點(diǎn)

在createShadowBitmap方法中,其實(shí)也可以看到需要?jiǎng)?chuàng)建bitmap對(duì)象。大家都知道bitmap比較容易造成內(nèi)存過(guò)大,如果是給recyclerView中的item設(shè)置陰影效果,那么如何避免重復(fù)創(chuàng)建,這時(shí)候可以用到緩存。所以可以在上面的基礎(chǔ)上再優(yōu)化一下代碼。

先創(chuàng)建key,主要是用于map集合的鍵。這里為何用對(duì)象Key作為map的鍵呢,這里是借鑒了glide緩存圖片的思路,可以創(chuàng)建Key對(duì)象的時(shí)候傳入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;  }}

然后存取操作如下所示

在查找的時(shí)候,通過(guò)Key進(jìn)行查找。注意:Bitmap需要同時(shí)滿足三個(gè)條件(高度、寬度、名稱)都相同時(shí)才能算是同一個(gè) Bitmap。

Key key = new Key("bitmap", shadowWidth, shadowHeight);Bitmap output = cache.get(key);if(output == null){  //根據(jù)寬高創(chuàng)建bitmap背景  output = Bitmap.createBitmap(shadowWidth, shadowHeight, Bitmap.Config.ARGB_8888);  cache.put(key, output);  LogUtil.v("bitmap對(duì)象-----","----直接創(chuàng)建對(duì)象,然后存入緩存之中---");} else {  LogUtil.v("bitmap對(duì)象-----","----從緩存中取出對(duì)象---");}

關(guān)于Android中怎么自定義一個(gè)陰影控件問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

分享名稱:Android中怎么自定義一個(gè)陰影控件
分享路徑:http://bm7419.com/article16/jjcpgg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化定制網(wǎng)站、虛擬主機(jī)Google、營(yíng)銷型網(wǎng)站建設(shè)網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

綿陽(yáng)服務(wù)器托管