Android Textview Outline (Kotlin)

July 25, 2018

NOTE: You can use shadow to simulate outline.

OutlineTextView class in Kotlin

class OutlineTextView : AppCompatTextView {

    private val defaultOutlineWidth = 0F
    private var isDrawing: Boolean = false

    private var outlineColor: Int = 0
    private var outlineWidth: Float = 0.toFloat()

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        if (attrs != null) {
            val a = context.obtainStyledAttributes(attrs, R.styleable.OutlineTextView)
            outlineColor = a.getColor(R.styleable.OutlineTextView_outlineColor, currentTextColor)
            outlineWidth = a.getDimension(R.styleable.OutlineTextView_outlineWidth, defaultOutlineWidth)

            a.recycle()
        } else {
            outlineColor = currentTextColor
            outlineWidth = defaultOutlineWidth
        }
        setOutlineWidth(TypedValue.COMPLEX_UNIT_PX, outlineWidth)
    }

    fun setOutlineColor(color: Int) {
        outlineColor = color
    }
    

    fun setOutlineWidth(unit: Int, width: Float) {
        outlineWidth = TypedValue.applyDimension(
                unit, width, context.resources.displayMetrics)
    }
    
    override fun invalidate() {
        // prevent onDraw.setTextColor force redraw
        if (isDrawing) return
        super.invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        // if (outlineWidth > 0) {
            isDrawing = true
            paint.style = Paint.Style.FILL
            super.onDraw(canvas)

            val currentTextColor = currentTextColor
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = outlineWidth
            setTextColor(outlineColor)
            super.onDraw(canvas)
            setTextColor(currentTextColor)

            isDrawing = false
        /*
        } else {
            super.onDraw(canvas)
        }
         */
    }
}

res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="OutlineTextView">
        <attr name="outlineColor" format="color" />
        <attr name="outlineWidth" format="dimension" />
    </declare-styleable>
</resources>

Sample usage

<com.myapp.view.OutlineTextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#fff"
    android:textSize="30sp"
    app:outlineColor="#000"
    app:outlineWidth="3"
/>
textView.setOutlineWidth(TypedValue.COMPLEX_UNIT_PX, 3f)
textView.setOutlineColor(color)

NOTE: Refer Android Get Color.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.