-
-
Save devjorgecastro/f2289544d40cbf70fcab1df05d2e0b06 to your computer and use it in GitHub Desktop.
Image with Blur Effect in 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
class BlurEffectActivity : ComponentActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
BlurEffectDemoTheme { | |
Surface( | |
color = MaterialTheme.colorScheme.background | |
) { | |
val bitmap = BitmapFactory | |
.decodeResource(LocalContext.current.resources, R.drawable.custom_image) | |
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { | |
LegacyBlurImage(bitmap, 25f) | |
} else { | |
BlurImage( | |
bitmap, | |
Modifier | |
.fillMaxSize() | |
.blur( | |
radiusX = 15.dp, | |
radiusY = 15.dp | |
) | |
) | |
} | |
} | |
} | |
} | |
} | |
} | |
@Composable | |
fun BlurImage( | |
bitmap: Bitmap, | |
modifier: Modifier = Modifier.fillMaxSize(), | |
) { | |
Image( | |
bitmap = bitmap.asImageBitmap(), | |
contentDescription = null, | |
contentScale = ContentScale.Crop, | |
modifier = modifier | |
) | |
} | |
@Composable | |
fun LegacyBlurImage( | |
bitmap: Bitmap, | |
blurRadio: Float, | |
modifier: Modifier = Modifier.fillMaxSize() | |
) { | |
val renderScript = RenderScript.create(LocalContext.current) | |
val bitmapAlloc = Allocation.createFromBitmap(renderScript, bitmap) | |
ScriptIntrinsicBlur.create(renderScript, bitmapAlloc.element).apply { | |
setRadius(blurRadio) | |
setInput(bitmapAlloc) | |
forEach(bitmapAlloc) | |
} | |
bitmapAlloc.copyTo(bitmap) | |
renderScript.destroy() | |
BlurImage(bitmap, modifier) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment