最近項(xiàng)目有一需求是這樣的衡便,一個類似于CardView的控件上覆蓋了一個Button亥宿。
效果圖
如果用CardView恋技,那么Button的z軸必須在CardView上方,那么Button就會出現(xiàn)陰影智袭,著不符合UED要求,所以就重新寫一個控件础拨,可以帶陰影效果氮块,并且忽略z軸。
** 關(guān)鍵思路**
自定義控件重寫onDraw方法诡宗,用畫筆Paint去繪制陰影滔蝉。
關(guān)鍵代碼:
@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(tǒng)
Tips:要繪制陰影,必須關(guān)閉硬件加速
項(xiàng)目地址:github.com/wangjianchi/ShadowLinearLayout.git