Created
March 16, 2021 09:28
-
-
Save markfarber/ccf2d57efa3ff5586a6485b305d7ca7a to your computer and use it in GitHub Desktop.
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
class RulerView @JvmOverloads constructor(ctx: Context, attrs: AttributeSet? = null) : View(ctx, attrs), AnkoLogger { | |
private var centimeters: Int = 0 | |
private var cmSize = 0f | |
private val lPaint = Paint() | |
private val tPaint = TextPaint() | |
companion object { | |
private const val LINE_WIDTH = 2f | |
private const val RULER_COLOR = Color.BLACK | |
} | |
init { | |
val pAlpha = 40 | |
tPaint.apply { | |
isAntiAlias = true | |
style = Paint.Style.FILL | |
textSize = 14f | |
color = RULER_COLOR | |
alpha = pAlpha | |
} | |
lPaint.apply { | |
isAntiAlias = true | |
style = Paint.Style.STROKE | |
strokeWidth = LINE_WIDTH | |
color = RULER_COLOR | |
alpha = pAlpha | |
} | |
} | |
fun init(width: Int) { | |
centimeters = width / 10 | |
} | |
override fun onSizeChanged(width: Int, height: Int, oldw: Int, oldh: Int) { | |
super.onSizeChanged(width, height, oldw, oldh) | |
cmSize = width.toFloat() / centimeters | |
} | |
override fun onDraw(canvas: Canvas?) { | |
// ifDebug { info { "::: @onDraw -> width = $width cmSize = $cmSize" } } | |
for (i in 0..centimeters) { | |
var offset = 0f | |
var lHeight: Float | |
var label: String? = null | |
when { | |
i == 0 -> { | |
lHeight = height * 0.65f | |
offset = LINE_WIDTH / 2 | |
} | |
i % 10 == 0 -> { | |
lHeight = height * 0.6f | |
label = i.toString() | |
} | |
i % 5 == 0 && i % 10 != 0 -> { | |
lHeight = height * 0.45f | |
} | |
else -> { | |
lHeight = height * 0.25f | |
} | |
} | |
if (i > 0 && i % centimeters == 0) offset = LINE_WIDTH / -2f | |
val lX = (i * cmSize) + offset | |
// ifDebug { info { "::: @onDraw -> lX = $lX" } } | |
canvas?.drawLine(lX, 0f, lX, lHeight, lPaint) | |
label?.let { | |
val tWidth = tPaint.measureText(it) | |
val tX = lX - tWidth / 2 | |
canvas?.drawText(it, tX, height.toFloat() - 2, tPaint) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment