Created
March 11, 2020 18:40
-
-
Save sergiandreplace/4478ae0b00671c19b098aa36272c4490 to your computer and use it in GitHub Desktop.
A semitransparent view with a rounded corner hole in it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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