I needed this as well so I created following Drawable
class. To get the solution that is wanted for this question you can use it like following:
val radius = min(view.width, view.height)
val bg = InvertedRectDrawable(Color.RED, radius, 0)
view.background = bg
Code
import android.graphics.*
import android.graphics.drawable.Drawable
class InvertedRectDrawable(
private val color: Int,
private val cornerRadius: Int,
private val border: Int,
private val contentColor: Int? = null
) : Drawable() {
private var paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
this.color = [email protected]
}
private var paint2: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
contentColor?.let {
this.color = it
}
}
private val path = Path()
override fun draw(canvas: Canvas) {
path.reset()
path.addRoundRect(
border.toFloat(),
border.toFloat(),
bounds.width().toFloat() - 2 * border.toFloat(),
bounds.height().toFloat() - 2 * border.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat(),
Path.Direction.CW
)
path.fillType = Path.FillType.INVERSE_EVEN_ODD
val s = canvas.save()
canvas.clipPath(path)
canvas.drawPaint(paint)
contentColor?.let {
canvas.restoreToCount(s)
path.fillType = Path.FillType.EVEN_ODD
canvas.clipPath(path)
canvas.drawPaint(paint2)
}
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
paint.colorFilter = colorFilter
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
}