Last active
October 27, 2020 11:03
-
-
Save AdrianoCelentano/29ea74656808efb5fb0206a057cf7f49 to your computer and use it in GitHub Desktop.
SinusWave with Jetpack Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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