Last active
March 12, 2020 02:56
-
-
Save m4kvn/e6caecd8f229805db273f3390ce79dc7 to your computer and use it in GitHub Desktop.
FontのMetricsを可視化するため雑につくったReplacementSpan
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 FontMetricsSpan : ReplacementSpan() { | |
| override fun draw( | |
| canvas: Canvas, | |
| text: CharSequence?, | |
| start: Int, | |
| end: Int, | |
| x: Float, | |
| top: Int, | |
| y: Int, | |
| bottom: Int, | |
| paint: Paint | |
| ) { | |
| canvas.save() | |
| val fontAscent = paint.fontMetricsInt.ascent | |
| val fontDescent = paint.fontMetricsInt.descent | |
| Log.d("FontMetricsSpan", "fontAscent=$fontAscent, fontDescent=$fontDescent, y=$y, top=$top") | |
| canvas.drawLine(y, Color.RED) | |
| canvas.drawLine(top, Color.BLUE) | |
| canvas.translate(0f, y.toFloat()) | |
| canvas.drawLine(fontAscent / 2, Color.CYAN) | |
| canvas.drawLine(fontAscent, Color.GREEN) | |
| canvas.drawLine(fontDescent, Color.MAGENTA) | |
| canvas.restore() | |
| } | |
| private fun Canvas.drawLine(y: Int, colorInt: Int) { | |
| val paint = Paint().apply { | |
| strokeWidth = 1f | |
| color = colorInt | |
| } | |
| drawLine(0f, y.toFloat(), width.toFloat(), y.toFloat(), paint) | |
| } | |
| override fun getSize( | |
| paint: Paint, | |
| text: CharSequence?, | |
| start: Int, | |
| end: Int, | |
| fm: Paint.FontMetricsInt? | |
| ): Int { | |
| text ?: return 0 | |
| if (fm != null) { | |
| val pfm = paint.fontMetricsInt | |
| fm.ascent = pfm.ascent | |
| fm.descent = pfm.descent | |
| fm.top = pfm.top | |
| fm.bottom = pfm.bottom | |
| } | |
| val fa = FloatArray(text.length) | |
| paint.getTextWidths(text, 0, text.length, fa) | |
| return fa.max()?.toInt() ?: 0 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment