Created
January 24, 2019 15:33
-
-
Save nwellis/82e0262c9fd2f0f088f90853c2215072 to your computer and use it in GitHub Desktop.
View to add a semitransparent overlay with a fully transparent square cutout
This file contains 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
import android.content.Context | |
import android.graphics.* | |
import android.util.AttributeSet | |
import android.view.View | |
import kotlin.math.max | |
import kotlin.math.min | |
class SquareCutoutOverlay( | |
context: Context, | |
attrs: AttributeSet? = null, | |
defStyleAttr: Int = 0 | |
) : View(context, attrs, defStyleAttr) { | |
constructor(context: Context): this(context, null, 0) | |
constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0) | |
private val semitransparentColor = Color.parseColor("#A6000000") | |
private val transparentPaint = Paint().apply { | |
color = Color.TRANSPARENT | |
strokeWidth = 10f | |
} | |
private val semitransparentPaint = Paint().apply { | |
color = Color.TRANSPARENT | |
strokeWidth = 10f | |
} | |
val path = Path() | |
init { | |
} | |
override fun onDrawForeground(canvas: Canvas) { | |
super.onDrawForeground(canvas) | |
val cornerRadii = 40f | |
val padding = 120f | |
val heightWidth = min(canvas.width, canvas.height) - padding*2 | |
val horizontalAdjust = (canvas.width - heightWidth)/2 //Distance between screen edge and square horizontally | |
val verticalAdjust = (canvas.height - heightWidth)/2 //Distance between screen edge and square vertically | |
val barcodeSquare = RectF( | |
padding, | |
verticalAdjust, | |
horizontalAdjust + heightWidth, | |
verticalAdjust + heightWidth | |
) | |
path.apply { | |
reset() | |
addRoundRect(barcodeSquare, cornerRadii, cornerRadii, Path.Direction.CW) | |
fillType = Path.FillType.INVERSE_EVEN_ODD | |
} | |
canvas.apply { | |
drawRoundRect(barcodeSquare, cornerRadii, cornerRadii, transparentPaint) | |
drawPath(path, semitransparentPaint) | |
clipPath(path) | |
drawColor(semitransparentColor) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment