Add opaque “shadow” (outline) to Android TextView

前端 未结 3 1886
借酒劲吻你
借酒劲吻你 2020-12-03 08:08

I have a TextView in my Activity to which I want to add a shadow. It is supposed to look like in OsmAnd (100% opaque):

But it looks like this:

3条回答
  •  温柔的废话
    2020-12-03 09:03

    I experienced the same issue, with calling setTextColor in onDraw causing infinite draw loop. I wanted to make my custom text view have a different fill color than the outline color when it rendered text. Which is why I was calling setTextColor multiple times in onDraw.

    I found an alternative solution using an OutlineSpan see https://github.com/santaevpavel/OutlineSpan. This is better than making the layout hierarchy complicated with multiple TextViews or using reflection and requires minimal changes. See the github page for more details. Example

    val outlineSpan = OutlineSpan(
        strokeColor = Color.RED,
        strokeWidth = 4F
    )
    val text = "Outlined text"
    val spannable = SpannableString(text)
    spannable.setSpan(outlineSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    
    // Set text of TextView
    binding.outlinedText.text = spannable 
    

提交回复
热议问题