Skip to content

Instantly share code, notes, and snippets.

@AdrianoCelentano
Last active October 27, 2020 11:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdrianoCelentano/29ea74656808efb5fb0206a057cf7f49 to your computer and use it in GitHub Desktop.
Save AdrianoCelentano/29ea74656808efb5fb0206a057cf7f49 to your computer and use it in GitHub Desktop.
SinusWave with Jetpack Compose
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.unit.dp
import com.adriano.compose.util.animationTimeMillis
import kotlin.math.sin
@Composable
fun SinusWave() {
https://github.com/alexjlockwood/bees-and-bombs-compose/blob/master/app/src/main/java/com/alexjlockwood/beesandbombs/demos/utils/AnimationUtils.kt
val millis by animationTimeMillis()
val path = remember { Path() }
Canvas(modifier = Modifier.fillMaxSize()) {
path.reset()
(1..WAVE_COUNT).forEach { waveIndex ->
val waveDistance = waveIndex.dp.toPx() * 4
translate(waveDistance, size.height / 2) {
drawWave(
path,
color = Color.Green.copy(alpha = 1f / waveIndex),
millis
)
}
}
}
}
fun DrawScope.drawWave(path: Path, color: Color, millis: Long) {
path.moveTo(0f, 0f)
(0..size.width.toInt()).forEach { x ->
val frequency = millis / 1000f
val altitude = 100 * (sin(millis / 1000f))
val waveLength = 0.015f
val y = sin(x * waveLength + (frequency)) * altitude
path.lineTo(x.toFloat(), y)
}
drawPath(
path = path,
color = color,
style = Stroke(
width = 2.dp.toPx(),
join = StrokeJoin.Round,
)
)
}
const val WAVE_COUNT = 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment