AnimationHelper.kt raw

   1  package io.github.domi04151309.alwayson.helpers
   2  
   3  import android.content.res.Resources
   4  import android.os.Handler
   5  import android.os.Looper
   6  import android.view.View
   7  import androidx.preference.PreferenceManager
   8  
   9  class AnimationHelper(private val xOffset: Float) {
  10      private val animationHandler = Handler(Looper.getMainLooper())
  11  
  12      fun animate(
  13          view: View,
  14          positionY: Float,
  15          duration: Int,
  16      ) {
  17          if (positionY == view.translationY) return
  18  
  19          view.translationX = xOffset + burnInOffset(view.resources)
  20          if (
  21              PreferenceManager.getDefaultSharedPreferences(view.context)
  22                  .getBoolean(P.ANIMATE_MOTION, P.ANIMATE_MOTION_DEFAULT)
  23          ) {
  24              var realFrame = 1
  25              val startPosition = view.translationY
  26              val numberOfFrames = duration / MILLISECONDS_PER_SECOND * FRAME_RATE
  27              val movementPerFrame =
  28                  (positionY + burnInOffset(view.resources) - startPosition) / (numberOfFrames - 1)
  29  
  30              for (preparedFrame in 1 until numberOfFrames) {
  31                  animationHandler.postDelayed({
  32                      view.translationY = startPosition + realFrame * movementPerFrame
  33                      realFrame++
  34                  }, MILLISECONDS_PER_SECOND / FRAME_RATE * preparedFrame)
  35              }
  36          } else {
  37              view.translationY = positionY + burnInOffset(view.resources)
  38          }
  39      }
  40  
  41      private fun burnInOffset(resources: Resources): Float =
  42          (
  43              (0 until MAX_OFFSET * 2).random() - MAX_OFFSET
  44          ) * resources.displayMetrics.density
  45  
  46      companion object {
  47          private const val MILLISECONDS_PER_SECOND: Long = 1000
  48          private const val MAX_OFFSET = 8
  49          private const val FRAME_RATE: Int = 15
  50      }
  51  }
  52