[Android]Create AnyView Background
LiHan
Posted on August 15, 2023
object ViewUtils {
fun generateBackgroundWithShadow(
view: View, @ColorRes backgroundColor: Int,
@DimenRes cornerRadius: Int,
@ColorRes shadowColor: Int,
@DimenRes elevation: Int,
shadowGravity: Int
): Drawable {
val cornerRadiusValue = view.context.resources.getDimension(cornerRadius)
val elevationValue = view.context.resources.getDimension(elevation).toInt()
val shadowColorValue = ContextCompat.getColor(view.context, shadowColor)
val backgroundColorValue = ContextCompat.getColor(view.context, backgroundColor)
val outerRadius = floatArrayOf(
cornerRadiusValue, cornerRadiusValue, cornerRadiusValue,
cornerRadiusValue, cornerRadiusValue, cornerRadiusValue, cornerRadiusValue,
cornerRadiusValue
)
val backgroundPaint = Paint()
backgroundPaint.style = Paint.Style.FILL
backgroundPaint.setShadowLayer(cornerRadiusValue, 0f, 0f, 0)
val shapeDrawablePadding = Rect()
shapeDrawablePadding.left = elevationValue
shapeDrawablePadding.right = elevationValue
val DY: Int
when (shadowGravity) {
Gravity.CENTER -> {
shapeDrawablePadding.top = elevationValue
shapeDrawablePadding.bottom = elevationValue
DY = 0
}
Gravity.TOP -> {
shapeDrawablePadding.top = elevationValue * 2
shapeDrawablePadding.bottom = elevationValue
DY = -1 * elevationValue / 3
}
Gravity.BOTTOM -> {
shapeDrawablePadding.top = elevationValue
shapeDrawablePadding.bottom = elevationValue * 2
DY = elevationValue / 3
}
else -> {
shapeDrawablePadding.top = elevationValue
shapeDrawablePadding.bottom = elevationValue * 2
DY = elevationValue / 3
}
}
val shapeDrawable = ShapeDrawable()
shapeDrawable.setPadding(shapeDrawablePadding)
shapeDrawable.paint.color = backgroundColorValue
shapeDrawable.paint.setShadowLayer(
cornerRadiusValue / 3,
0f,
DY.toFloat(),
shadowColorValue
)
view.setLayerType(LAYER_TYPE_SOFTWARE, shapeDrawable.paint)
shapeDrawable.shape = RoundRectShape(outerRadius, null, null)
val drawable = LayerDrawable(arrayOf<Drawable>(shapeDrawable))
drawable.setLayerInset(
0,
elevationValue,
elevationValue * 2,
elevationValue,
elevationValue * 2
)
return drawable
}
}
Reference:
https://medium.com/@ArmanSo/take-control-of-views-shadow-android-c6b35ba573e9
💖 💪 🙅 🚩
LiHan
Posted on August 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
githubcopilot AI Innovations at Microsoft Ignite 2024 What You Need to Know (Part 2)
November 29, 2024