Skip to content

Instantly share code, notes, and snippets.

@sergiandreplace
Created March 11, 2020 18:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergiandreplace/4478ae0b00671c19b098aa36272c4490 to your computer and use it in GitHub Desktop.
Save sergiandreplace/4478ae0b00671c19b098aa36272c4490 to your computer and use it in GitHub Desktop.
A semitransparent view with a rounded corner hole in it
class OverlayWithHoleImageView(context: Context?, attrs: AttributeSet?) : androidx.appcompat.widget.AppCompatImageView(context, attrs) {
private var rect: RectF? = null
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#a8000000")
style = Paint.Style.FILL
}
private val addMode = PorterDuffXfermode(PorterDuff.Mode.ADD)
private val clearMode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
private val radius = 40.dp
private val margin = 32.dp
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
rect = RectF(
margin + paddingLeft,
margin + paddingTop,
w - margin - paddingRight,
h - margin - paddingBottom
)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
rect?.let {
paint.xfermode = addMode
canvas.drawPaint(paint)
paint.xfermode = clearMode
canvas.drawRoundRect(it, radius, radius, paint)
}
}
init {
setLayerType(View.LAYER_TYPE_HARDWARE, null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment