最近項目有一需求是這樣的,一個類似于CardView的控件上覆蓋了一個Button。
效果圖
如果用CardView,那么Button的z軸必須在CardView上方,那么Button就會出現陰影,著不符合UED要求,所以就重新寫一個控件,可以帶陰影效果,并且忽略z軸。
** 關鍵思路**
自定義控件重寫onDraw方法,用畫筆Paint去繪制陰影。
關鍵代碼:
@Override
protected voidonDraw(Canvas canvas) {
setLayerType(LAYER_TYPE_SOFTWARE, null);//必須硬件不加速
Paint paint =newPaint();
paint.setColor(bgColor);
paint.setShadowLayer(shadowRadius,offset_x,offset_y,shadowColor);
canvas.drawRoundRect(newRectF(shadowRadius+offset_x,shadowRadius+offset_y,width-shadowRadius+offset_x,height-shadowRadius+offset_y),radius_x,radius_y,paint);
super.onDraw(canvas);
}
shadowColor : 陰影顏色
bgColr:背景顏色
shadowRadius:陰影半徑
offset_x:陰影x軸偏移量
offset_y:陰影y軸偏移量
radius_x:圓角半徑x
radius_y:圓角半徑y
Tips:要繪制陰影,必須關閉硬件加速
項目地址:github.com/wangjianchi/ShadowLinearLayout.git