Created
November 21, 2017 12:04
-
-
Save kubode/664fc5b1f1b0d34e3ee95819d6df625c to your computer and use it in GitHub Desktop.
MaskableTextView
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
import android.content.Context | |
import android.graphics.Canvas | |
import android.graphics.Paint | |
import android.graphics.PorterDuff | |
import android.graphics.PorterDuffXfermode | |
import android.graphics.drawable.Drawable | |
import android.support.v7.widget.AppCompatTextView | |
import android.util.AttributeSet | |
class MaskableTextView @JvmOverloads constructor( | |
context: Context, | |
attrs: AttributeSet? = null, | |
defStyleAttr: Int = android.R.attr.textViewStyle | |
) : AppCompatTextView(context, attrs, defStyleAttr) { | |
private val maskPaint = Paint().apply { | |
xfermode = PorterDuffXfermode(PorterDuff.Mode.MULTIPLY) | |
} | |
var maskDrawable: Drawable? = null | |
set(value) { | |
field = value | |
value?.state = drawableState | |
invalidate() | |
} | |
override fun drawableStateChanged() { | |
super.drawableStateChanged() | |
maskDrawable?.let { if (it.isStateful && it.setState(drawableState)) invalidate() } | |
} | |
override fun onDraw(canvas: Canvas) { | |
canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG) | |
super.onDraw(canvas) | |
maskDrawable?.let { | |
canvas.saveLayer(null, maskPaint, Canvas.ALL_SAVE_FLAG) | |
it.setBounds(0, 0, canvas.width, canvas.height) | |
it.draw(canvas) | |
canvas.restore() | |
} | |
canvas.restore() | |
} | |
init { | |
val arr = context.obtainStyledAttributes(attrs, R.styleable.MaskableTextView, defStyleAttr, 0) | |
maskDrawable = arr.getDrawable(R.styleable.MaskableTextView_maskDrawable) | |
arr.recycle() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment