Skip to content

Instantly share code, notes, and snippets.

@ZieIony
Last active January 31, 2022 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZieIony/d41401230120d5dbffdc5d84e7fa6529 to your computer and use it in GitHub Desktop.
Save ZieIony/d41401230120d5dbffdc5d84e7fa6529 to your computer and use it in GitHub Desktop.
package com.example
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
class PulseView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = 0xff6DA9D7.toInt() }
private var button = BitmapFactory.decodeResource(resources, R.drawable.button)
private var touch = PointF(0.0f, 0.0f)
private var startTime = System.currentTimeMillis()
private val size = SIZE_DP * resources.displayMetrics.density
private val interpolator = DecelerateInterpolator()
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
touch = PointF(event.x, event.y)
return true
}
private fun lerp(a: Float, b: Float, t: Float) = a * (1 - t) + b * t
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val time = System.currentTimeMillis()
for (r in 0..RIPPLE_COUNT) {
val offset = INTERVAL_MS * r / RIPPLE_COUNT
val t = (time - startTime + offset) % INTERVAL_MS / INTERVAL_MS
val interpolatedT = interpolator.getInterpolation(t)
paint.alpha = (255 - interpolatedT * 255).toInt()
canvas.drawCircle(
lerp(touch.x, width / 2.0f, t),
lerp(touch.y, height / 2.0f, t),
interpolatedT * size,
paint
)
}
paint.alpha = 255
canvas.drawBitmap(button, touch.x - button.width / 2, touch.y - button.height / 2, paint)
postInvalidate()
}
companion object {
const val RIPPLE_COUNT = 2
const val INTERVAL_MS = 1000.0f
const val SIZE_DP = 100.0f
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment