Last active
December 26, 2023 04:01
-
-
Save dladukedev/fafd2a5483fa2414b492e2c2830b21ba to your computer and use it in GitHub Desktop.
Tilling Image Background with ShaderBrush and ImageShader
This file contains hidden or 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
package com.dladukedev.tiledimage | |
import androidx.compose.foundation.background | |
import androidx.compose.foundation.layout.Box | |
import androidx.compose.foundation.layout.size | |
import androidx.compose.runtime.Composable | |
import androidx.compose.runtime.remember | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.draw.drawBehind | |
import androidx.compose.ui.graphics.Brush | |
import androidx.compose.ui.graphics.Color | |
import androidx.compose.ui.graphics.ColorFilter | |
import androidx.compose.ui.graphics.ImageBitmap | |
import androidx.compose.ui.graphics.ImageShader | |
import androidx.compose.ui.graphics.LinearGradientShader | |
import androidx.compose.ui.graphics.ShaderBrush | |
import androidx.compose.ui.graphics.TileMode | |
import androidx.compose.ui.res.imageResource | |
import androidx.compose.ui.tooling.preview.Preview | |
import androidx.compose.ui.unit.dp | |
@Composable | |
fun Modifier.starBackground(): Modifier { | |
val image = ImageBitmap.imageResource(R.drawable.img_star_background) | |
val starBrush = remember(image) { ShaderBrush(ImageShader(image, TileMode.Repeated, TileMode.Repeated)) } | |
return this.background(brush = starBrush) | |
} | |
@Composable | |
fun Modifier.starBackground(color: Color): Modifier { | |
val image = ImageBitmap.imageResource(R.drawable.img_star_background) | |
val starBrush = remember(image) { ShaderBrush(ImageShader(image, TileMode.Repeated, TileMode.Repeated)) } | |
return this.drawBehind { | |
drawRect(starBrush, colorFilter = ColorFilter.tint(color)) | |
} | |
} | |
@Preview | |
@Composable | |
fun PreviewStarBackground() { | |
Box(modifier = Modifier.size(400.dp).starBackground()) | |
} | |
@Preview | |
@Composable | |
fun PreviewStarBackgroundBlue() { | |
Box(modifier = Modifier.size(400.dp).starBackground(Color.Blue)) | |
} | |
@Preview | |
@Composable | |
fun PreviewStarBackgroundComplex() { | |
Box(modifier = Modifier.size(400.dp) | |
.background(Color.White) | |
.starBackground(Color.Blue) | |
.background(Brush.verticalGradient( | |
Pair(.15f, Color.White), | |
Pair(.5f, Color.White.copy(alpha = 0.6f)), | |
Pair(.85f, Color.White.copy(alpha = 0.4f)), | |
Pair(1f, Color.Transparent)) | |
) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment