Skip to content

Instantly share code, notes, and snippets.

@Zulqurnain
Created September 7, 2021 07:14
Show Gist options
  • Save Zulqurnain/293ac28524c0664cff6e7bd5d08e3907 to your computer and use it in GitHub Desktop.
Save Zulqurnain/293ac28524c0664cff6e7bd5d08e3907 to your computer and use it in GitHub Desktop.
Get One Sides Shadow In View
/**
* Get Shadow Drawable with most elevation on provided shadowGravity Attribute
*/
fun getBoxShadowBackground(
view: View,
@ColorRes backgroundColor: Int = android.R.color.white,
radiusInDP: Float = view.convertDpTpPx(5F),
@ColorRes shadowColor: Int = android.R.color.black,
elevation: Int = 0,
shadowGravity: Int = Gravity.BOTTOM
): Drawable? {
val shadowColorValue = ContextCompat.getColor(view.context, shadowColor)
val backgroundColorValue = ContextCompat.getColor(view.context, backgroundColor)
val outerRadius = floatArrayOf(
radiusInDP, // top-left
radiusInDP, // top-left
radiusInDP, // top-right
radiusInDP, // top-right
radiusInDP, // bottom-right
radiusInDP, // bottom-right
radiusInDP, // bottom-left
radiusInDP // bottom-left
)
val backgroundPaint = Paint()
backgroundPaint.style = Paint.Style.FILL
backgroundPaint.setShadowLayer(radiusInDP, 0f, 0f, 0)
val shapeDrawablePadding = Rect()
shapeDrawablePadding.left = elevation
shapeDrawablePadding.right = elevation
val DY: Int
when (shadowGravity) {
Gravity.CENTER -> {
shapeDrawablePadding.top = elevation
shapeDrawablePadding.bottom = elevation
DY = 0
}
Gravity.TOP -> {
shapeDrawablePadding.top = elevation * 2
shapeDrawablePadding.bottom = elevation
DY = -1 * elevation / 3
}
Gravity.BOTTOM -> {
shapeDrawablePadding.top = elevation
shapeDrawablePadding.bottom = elevation * 2
DY = elevation / 3
}
else -> {
shapeDrawablePadding.top = elevation
shapeDrawablePadding.bottom = elevation * 2
DY = elevation / 3
}
}
val shapeDrawable = ShapeDrawable()
shapeDrawable.setPadding(shapeDrawablePadding)
shapeDrawable.paint.color = backgroundColorValue
shapeDrawable.paint.setShadowLayer(radiusInDP / 3, 0f, DY.toFloat(), shadowColorValue)
view.setLayerType(View.LAYER_TYPE_SOFTWARE, shapeDrawable.paint)
shapeDrawable.shape = RoundRectShape(outerRadius, null, null)
val drawable = LayerDrawable(arrayOf<Drawable>(shapeDrawable))
drawable.setLayerInset(
0,
elevation,
elevation * 2,
elevation,
elevation * 2
)
return drawable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment