目录

效果展示

实现原理
继承RelativeLayout并实现dispatchDraw方法,然后在dispatchDraw方法的super.dispatchDraw(canvas)之前绘制阴影,而阴影则是通过利用Canvas绘制矩形或圆角矩形并给绘制矩形的画笔设置阴影效果来实现的。
代码展示
class ShadownLayout:RelativeLayout {
private var mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var mMargen:Float = ConvertUtils.dp2px(8F).toFloat()//留出8dp的阴影位置
init {
setLayerType(View.LAYER_TYPE_SOFTWARE, null)//关闭硬件加速
mPaint.setShadowLayer(mMargen,0F,0F, Color.parseColor("#ff0000"))//设置画笔的阴影
mPaint.color = Color.parseColor("#ffffff")//设置画笔的颜色
mPaint.style = Paint.Style.FILL//设置画笔样式为填充
}
constructor(context: Context) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun dispatchDraw(canvas: Canvas?) {
canvas!!.drawRoundRect(RectF(mMargen,mMargen, width-mMargen,height-mMargen),mMargen,mMargen,mPaint)//在绘制子控件之前绘制阴影,否则会遮住子控件
super.dispatchDraw(canvas)
}
}
使用方法
跟平时使用RelativeLayout一样,但是需要注意的是这里需要给ShadownLayout添加与阴影大小相同的内边距,否则子控件可能会与阴影重合。
<?xml version="1.0" encoding="utf-8"?>
<com.hehuidai.customview.one.shadownview.ShadownLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="80dp">
<TextView
android:id="@+id/item_shadown_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="我是小小文字" />
</com.hehuidai.customview.one.shadownview.ShadownLayout>
网友评论