Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Last active September 3, 2019 10:37
Show Gist options
  • Save addeeandra/33a9b3359cedd55c6541686499f560a0 to your computer and use it in GitHub Desktop.
Save addeeandra/33a9b3359cedd55c6541686499f560a0 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ClipBoxView">
<attr name="ratio_width" format="float" />
<attr name="ratio_height" format="float" />
<attr name="border_width" format="integer" />
<attr name="border_color" format="color" />
<attr name="frame_color" format="color" />
</declare-styleable>
</resources>
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Region
import android.os.Build
import android.util.AttributeSet
import android.view.View
class ClipBoxView(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) {
private val frameBoxPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
private val borderBoxPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
private var mWidthRatio = 1f / 10f
private var mHeightRatio = 1f / 4f
private var mBorderWidth = 2
init {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.ClipBoxView,
0, 0
).apply {
mWidthRatio = 1f / getFloat(R.styleable.ClipBoxView_ratio_width, 10f)
mHeightRatio = 1f / getFloat(R.styleable.ClipBoxView_ratio_height, 4f)
mBorderWidth = getInteger(R.styleable.ClipBoxView_border_width, 2)
borderBoxPaint.color = getColor(
R.styleable.ClipBoxView_border_color,
Color.parseColor("#FF0000")
)
frameBoxPaint.color = getColor(
R.styleable.ClipBoxView_frame_color,
Color.parseColor("#55000000")
)
}
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
clipOutRect(
width * mWidthRatio,
height * mHeightRatio,
width * (1f - mWidthRatio),
height * (1f - mHeightRatio)
)
} else {
clipRect(
width * mWidthRatio,
height * mHeightRatio,
width * (1f - mWidthRatio),
height * (1f - mHeightRatio),
Region.Op.DIFFERENCE
)
}
drawRect(0f, 0f, width * 1f, height * 1f, frameBoxPaint)
drawRect(
width * mWidthRatio - mBorderWidth,
height * mHeightRatio - mBorderWidth,
width * (1f - mWidthRatio) + mBorderWidth,
height * (1f - mHeightRatio) + mBorderWidth,
borderBoxPaint
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment