Skip to content

Instantly share code, notes, and snippets.

@cuub
Created September 17, 2019 16:11
Show Gist options
  • Save cuub/074b835b39a6ab565dbd2497ac114b60 to your computer and use it in GitHub Desktop.
Save cuub/074b835b39a6ab565dbd2497ac114b60 to your computer and use it in GitHub Desktop.
Custom TextView that fades the final part of the text on the last line. maxLines attribute is required
import android.content.Context
import android.graphics.*
import android.support.v7.widget.AppCompatTextView
import android.text.Layout
import android.util.AttributeSet
class FadeOutTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttribute: Int = android.R.attr.textViewStyle
) : AppCompatTextView(context, attrs, defStyleAttribute) {
companion object {
private const val FADE_LENGTH = 3
}
private val shader: Shader
private val mMatrix: Matrix = Matrix()
private val paint: Paint = Paint()
private val bounds: Rect = Rect()
init {
shader = LinearGradient(0f, 0f, 1f, 0f, 0, -0x1000000, Shader.TileMode.CLAMP)
paint.shader = shader
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
}
override fun onDraw(canvas: Canvas) {
val layout = layout
val line = maxLines - 1
val isRtl = layout.getParagraphDirection(line) == Layout.DIR_RIGHT_TO_LEFT
getLineBounds(line, bounds)
val fadeLength = bounds.width() / FADE_LENGTH
if (isRtl) {
bounds.right = bounds.left + fadeLength
} else {
bounds.left = bounds.right - fadeLength
}
val saveCount = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null)
super.onDraw(canvas)
// Adjust and set the Shader Matrix
mMatrix.reset()
mMatrix.setScale(fadeLength.toFloat(), 1f)
if (isRtl) {
matrix.postRotate(180f, fadeLength / 2f, 0f)
}
mMatrix.postTranslate(bounds.left.toFloat(), 0f)
shader.setLocalMatrix(mMatrix)
canvas.drawRect(bounds, paint)
canvas.restoreToCount(saveCount)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment