|

How to set Image Aspect Ratio in Android Jetpack Compose

The aspect ratio is the proportion of an image’s width to its height. It plays a crucial role in the design of a mobile app as it determines how an image will be displayed on different screen sizes and orientations.

In this blog post, let’s learn how to set the aspect ratio to an image in Jetpack Compose.

The Image composable is used to display images in Jetpack Compose. Using Modifier.aspectRatio modifier we can set the desired aspect ratio. The data type of ratio value must be a Float.

See the code snippet given below.

Image(painter = painterResource(id = R.drawable.tattoo),
        contentDescription = null,
        modifier = Modifier.aspectRatio(16f / 9f)
    )

Following is the complete code for reference.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    ImageExample()
                }
            }
        }
    }
}

@Composable
fun ImageExample() {
    Image(painter = painterResource(id = R.drawable.tattoo),
        contentDescription = null,
        modifier = Modifier.aspectRatio(16f / 9f)
    )
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        ImageExample()
    }
}

I hope this Android tutorial to change the image aspect ratio in Jetpack Compose is helpful for you.

If you want to change the image tint color then see this blog post on how to set image tint color in Jetpack compose.

Similar Posts

Leave a Reply