Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Created May 22, 2020 12:18
Show Gist options
  • Save addeeandra/6d33b8a1592d1611cabcca70061de26f to your computer and use it in GitHub Desktop.
Save addeeandra/6d33b8a1592d1611cabcca70061de26f to your computer and use it in GitHub Desktop.
Button with Shadow. What else?
import android.content.Context
import android.graphics.BlurMaskFilter
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.widget.TextView
class ButtonWithShadow : TextView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
private val mShadowBlur = 56f
private val mShadowOffsetW = mShadowBlur / 56f * 64f
private val mShadowOffsetH = mShadowBlur / 56f * 48f
private val mBackgroundRatio = 42 / mShadowBlur
private var mShadowOffsetY = 24f
private var mRadius = 24f
private val shadowPaint by lazy {
Paint(0).apply {
color = Color.parseColor("#00B761")
style = Paint.Style.FILL
maskFilter = BlurMaskFilter(mShadowBlur, BlurMaskFilter.Blur.NORMAL)
}
}
private val rectPaint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#00B761")
style = Paint.Style.FILL
}
}
init {
setLayerType(LAYER_TYPE_SOFTWARE, null)
}
override fun onDraw(canvas: Canvas) {
canvas.drawRoundRect(
mShadowOffsetW,
mShadowOffsetH + mShadowOffsetY,
width - mShadowOffsetW,
height - mShadowOffsetH,
mRadius,
mRadius,
shadowPaint
)
canvas.drawRoundRect(
mShadowOffsetW * mBackgroundRatio,
mShadowOffsetH * mBackgroundRatio,
width - mShadowOffsetW * mBackgroundRatio,
height - mShadowOffsetH * mBackgroundRatio,
mRadius,
mRadius,
rectPaint
)
super.onDraw(canvas)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment