Created
February 2, 2016 04:23
-
-
Save dgmltn/2dd165c0ae8bc948cf3c to your computer and use it in GitHub Desktop.
A TextView that supports stroked and filled text
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
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="StrokedText"> | |
<attr name="textStrokeColor" format="color"/> | |
<attr name="textStrokeWidth" format="dimension"/> | |
</declare-styleable> | |
</resources> |
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.Canvas | |
import android.graphics.Paint | |
import android.util.AttributeSet | |
import android.widget.TextView | |
class StrokedTextView(context: Context, attrs: AttributeSet?) : TextView(context, attrs) { | |
val DEFAULT_STROKE_WIDTH = 0f | |
var strokeColor = 0 | |
var strokeWidth = DEFAULT_STROKE_WIDTH | |
init { | |
if (attrs != null) { | |
val a = context.obtainStyledAttributes(attrs, R.styleable.StrokedText) | |
strokeColor = a.getColor(R.styleable.StrokedText_textStrokeColor, currentTextColor) | |
strokeWidth = a.getDimension(R.styleable.StrokedText_textStrokeWidth, DEFAULT_STROKE_WIDTH) | |
a.recycle() | |
} | |
else { | |
strokeColor = currentTextColor | |
} | |
} | |
override fun onDraw(canvas: Canvas) { | |
// Set paint to fill mode | |
val p = paint | |
p.style = Paint.Style.FILL | |
// Draw the fill part of text | |
super.onDraw(canvas) | |
if (strokeWidth > 0) { | |
// Save the text color | |
val current = textColors | |
// Set paint to stroke mode and specify | |
// stroke color and width | |
p.style = Paint.Style.STROKE | |
p.strokeWidth = strokeWidth | |
setTextColor(strokeColor) | |
// Draw text stroke | |
super.onDraw(canvas) | |
// Revert the color back to the one | |
// initially specified | |
setTextColor(current) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment