Hi guys, today I want to share this little article where I briefly explain how to create a blurry image on Android. Without so much introduction, let’s get to the point. 😎
Blur is a visual effect that is often used in graphics software to reduce the clarity or sharpness of an image or video. It can be used for a variety of purposes, such as to reduce distractions in the background of a photo or to create a more visually pleasing composition.
Photo by Unsplash
As developers, at some point we may have a need to create blurry images, so today I want to share with you a solution that is backward compatible with Android API 31.
When we work with Jetpack Compose, we can apply a blur effect in a very simple way using the blur extension function of the Modifier interface.
The problem with the example above is that if it runs on versions below Android 12, we will not see any effect because this implementation is only allowed in Android 12 (API level 31) or higher versions.
So we will have to verify if we are running the application on versions equal to or greater than Android 12.
The first thing we will do is create our code for versions prior to Android 12. For this, we will use RenderScript and ScriptIntrinsicBlur. We will create a composable function called “LegacyBlurImage” that will give us an Image product of a previously processed bitmap.
@Composable
private 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)
}
We will also create a composable function that we will call “BlurImage” with which we will create the composable for the image we want to display.
@Composable
fun BlurImage(
bitmap: Bitmap,
modifier: Modifier = Modifier.fillMaxSize(),
) {
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = modifier
)
}
Finally we call our functions checking the version of Android that the device has.
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)
)
}
Result
You can see the complete code here.
If you like my content and want to support my work, you can give me a cup of coffee ☕️ 🥰
Follow me in
Twitter: @devjcastro
Linkedin: dev-jorgecastro
Top comments (0)