android 使用setShadowLayer创建简单的阴影
现在Android项目使用阴影的需求越来越多了,下面我价绍一下创建阴影的代码。一般来说ui切图的阴影虽然好看舒服一点,但是不利于动态定制,如果代码里能自己定制多好啊。主要的使用的api是paint.setShaodwLayout。
class SimpleShadowBuilder {
private var shadowRadius: Float = 2f.dpToPxFloat()
private var solidColor: Int = Color.WHITE
private var shadowColor: Int = Color.DKGRAY
private var dx = 0f
private var dy = 0f
private var width: Int = -1
private var height: Int = -1
private var shape: Shape = OvalShape()
fun setShadowRadius(shadowRadius: Float): SimpleShadowBuilder {
this.shadowRadius = shadowRadius.coerceAtLeast(0f)
return this
}
fun setShadowColor(color: Int): SimpleShadowBuilder {
shadowColor = color
return this
}
fun setSolidColor(color: Int): SimpleShadowBuilder {
this.solidColor = color
return this
}
fun setShadowDx(dx: Float): SimpleShadowBuilder {
this.dx = dx
return this
}
fun setShadowDy(dy: Float): SimpleShadowBuilder {
this.dy = dy
return this
}
fun width(width: Int): SimpleShadowBuilder {
this.width = width
return this
}
fun height(height: Int): SimpleShadowBuilder {
this.height = height
return this
}
fun setShape(shape: Shape): SimpleShadowBuilder {
this.shape = shape
return this
}
fun roundShape(cornerRadius: Float): SimpleShadowBuilder {
val outerRadius = floatArrayOf(
cornerRadius, cornerRadius, cornerRadius, cornerRadius,
0f, 0f, 0f, 0f
)
this.shape = RoundRectShape(outerRadius, null, null)
return this
}
private fun build(): Drawable {
val shadowDrawable = ShapeDrawable()
shadowDrawable.paint.setShadowLayer(
shadowRadius,
dx,
dy,
shadowColor
)
shadowDrawable.paint.style = Paint.Style.FILL
shadowDrawable.paint.color = solidColor
shadowDrawable.shape = this.shape
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
InsetDrawable(shadowDrawable, shadowRadius)
} else {
InsetDrawable(shadowDrawable, shadowRadius.toInt())
}
}
fun into(view: View) {
val parent = view.parent as? ViewGroup
parent?.clipChildren = false
parent?.clipToPadding = false
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
view.background = build()
}
}
下面贴上使用效果
|