I am trying to make a Composable which I can ruse by passing image of any size to fill its Width by using
compose_version = 1.0.0-beta07
@Composable
fun image(image:Int){
Image(painter = painterResource(image),
contentDescriptionn = null, contentScale = ContentScale.FillWidth)
}
When I am passing other images it's working but when I am passing a image which width and height are same it's not working
How to fix this?
Try passing size related modifier, like Modifier.fillMaxWidth()
, Modifier.width(100.dp)
, Modifier.size(24.dp)
, depending on your need. If square image is required then add Modifier.aspectRatio(1f)
.
@Composable
fun Image(modifier: Modifier = Modifier, @DrawableRes image: Int){
Image(
modifier = modifier,
painter = painterResource(image),
contentDescription = null,
contentScale = ContentScale.FillWidth)
}
Image(Modifier.fillMaxWidth(), image = R.drawable.sq1)
If image always needs to fill full available width then
@Composable
fun Image(modifier: Modifier = Modifier, @DrawableRes image: Int){
Image(
modifier = modifier.fillMaxWidth(),
painter = painterResource(image),
contentDescription = null,
contentScale = ContentScale.FillWidth)
}
Image(image = R.drawable.sq1)
Update: Clarification for rectangular images
@Composable
fun Image(modifier: Modifier = Modifier, @DrawableRes image: Int){
Image(
modifier = modifier.fillMaxWidth().aspectRatio(1f),
painter = painterResource(image),
contentDescription = null,
contentScale = ContentScale.FillWidth)
}
For a given available width, the height of the Image composable will be calculated using aspect ratio. So image composable will be square with the maximum width possible.
Now comes the scaling to place the image inside this square composable. Here ContentScale.FillWidth
will be used to determine position and scaling of image.
For portrait images, the image will fill full width of the square and will be centered vertically cropping out some upper and lower parts of the image.
For landscape images, again due to ContentScale.FillWidth
scaling, the full width of the square will be filled by image but since the height of the image isn't sufficient so the image will be centered vertically, leaving blank space in the upper and lower part of the square.