Skip to content

Instantly share code, notes, and snippets.

@oguzhanaslann
Created November 20, 2023 19:45
Show Gist options
  • Select an option

  • Save oguzhanaslann/0a8fd9738a61e23acf07e07c5888a0ce to your computer and use it in GitHub Desktop.

Select an option

Save oguzhanaslann/0a8fd9738a61e23acf07e07c5888a0ce to your computer and use it in GitHub Desktop.
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RectShape
import android.graphics.drawable.shapes.RoundRectShape
import android.graphics.drawable.shapes.Shape
class ShapeDrawableBuilder {
private var shape: Shape? = null
private var width = 0
private var height = 0
private var backgroundColor = 0
private var borderColor = 0
private var borderWidth = 0
fun setShape(shape: Shape?): ShapeDrawableBuilder {
this.shape = shape
return this
}
fun setSize(width: Int, height: Int): ShapeDrawableBuilder {
this.width = width
this.height = height
return this
}
fun setBackgroundColor(color: Int): ShapeDrawableBuilder {
backgroundColor = color
return this
}
fun setBorderColor(color: Int): ShapeDrawableBuilder {
borderColor = color
return this
}
fun setBorderWidth(width: Int): ShapeDrawableBuilder {
borderWidth = width
return this
}
fun build(): Drawable {
val layers = mutableListOf<Drawable>()
if (shape == null) {
shape = RectShape()
}
// Create a shape drawable for the background
val backgroundDrawable = ShapeDrawable(shape)
val backgroundPaint = backgroundDrawable.paint
if (width > 0 && height > 0) {
backgroundDrawable.setBounds(0, 0, width, height)
}
// Set background color
if (backgroundColor != 0) {
backgroundPaint.style = Paint.Style.FILL
backgroundPaint.color = backgroundColor
}
layers.add(backgroundDrawable)
// Create a shape drawable for the border
if (borderWidth > 0 && borderColor != 0) {
val borderDrawable = ShapeDrawable(shape)
val borderPaint = borderDrawable.paint
borderPaint.style = Paint.Style.STROKE
borderPaint.strokeWidth = borderWidth.toFloat()
borderPaint.color = borderColor
layers += borderDrawable
}
return LayerDrawable(layers.toTypedArray())
}
}
fun roundedRectangleShape(cornerRadius: Float): RoundRectShape {
val outerRadii = FloatArray(8)
for (i in 0..7) {
outerRadii[i] = cornerRadius
}
return RoundRectShape(outerRadii, null, null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment