3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【備忘録】Androidで魔法を使っているみたいなタッチエフェクト

Posted at

##画面に触るたびに散る光の粉っぽいエフェクト

screencast-Genymotion-2021-07-21_17.25.14.665.gif

こんな感じのエフェクト。

MyEffect.kt

@SuppressLint("ViewConstructor")
class MyEffect(context: Context, private val eventX: Float, private val eventY: Float): View(context) {
    private var paint = Paint()

    override fun onDraw(canvas: Canvas?) {
        canvas?.drawColor(Color.TRANSPARENT)
        val color = Color.WHITE
        paint.apply {
            setColor(color)
            alpha = 200
            isAntiAlias = true
            style = Paint.Style.FILL
        }
        canvas?.drawCircle(eventX, eventY, 2f, paint)
        for (count in 1..4) {
            val scatter1 = (-30..30).random().toFloat()
            val scatter2 = (-30..30).random().toFloat()
            val size = (1..6).random().toFloat()
            canvas?.drawCircle(eventX + scatter1, eventY + scatter2, size, paint)
        }
    }
}

MainActivity.kt

 override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_UP || event?.action == MotionEvent.ACTION_MOVE) {
            val myEffect = MyEffect(this, event.x, event.y)
            binding.parentLayout.addView(myEffect)
            myEffect.run {
                animate().alpha(0f).setDuration(800)
            }
            handler.postDelayed({ binding.parentLayout.removeView(myEffect) }, 810)
            return true
        }
        return false
    }

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?