Reputation: 1662
I want to set a shape drawable to an image in compose, the drawable look like this cureved_rect.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FBCCBD" />
<corners android:radius="8dp" />
</shape>
I try the below snipet to load the shape
Image(painter = painterResource(id = R.drawable.cureved_rect),
contentDescription = null,
modifier = Modifier
.padding(32.dp)
.fillMaxWidth()
.height(200.dp)
.constrainAs(image) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
})
But it is not working, the app crash with an exception java.lang.IllegalArgumentException:Only VectorDrawables and rasterised asset types are supported ex PNG,JPG 1 . How to load shape drawable in compose 2 . Load colour resource in the compose image
Upvotes: 17
Views: 10932
Reputation: 363459
The best solution is to use the Shape
provided by Compose.
Something like:
Box(
modifier = Modifier
.size(200.dp)
.background(Color(0xFFFBCCBD), shape = RoundedCornerShape(16.dp))
)
Otherwise if you want to use drawable resource you can use the coil-compose
version:
Something like:
Image(
rememberImagePainter( ContextCompat.getDrawable(context,R.drawable.shape)),
contentDescription = "Background",
modifier = Modifier.size(200.dp)
)
Upvotes: 16
Reputation: 10717
you have to do like this:
@Composable
fun RoundedCornerShapeDemo() {
ImageResource(shape = RoundedCornerShape(10.dp))
}
@Composable
fun ImageResource(shape: Shape) {
Column(modifier = Modifier.fillMaxSize()) {
val image: Painter = painterResource(id = R.drawable.ic_launcher_background)
Image(painter = image, contentDescription = "", modifier = Modifier
.size(90.dp)
.clip(shape))
}
}
In your activity
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ShapeImageApplicationTheme {
Surface(color = MaterialTheme.colors.background) {
RoundedCornerShapeDemo()
}
}
}
}
}
Upvotes: 0
Reputation: 3227
Here is a workaround, instead of using Image composable function, you can use AndroidView so your code would be similar to this:
AndroidView(factory = {
val view = LayoutInflater.from(it).inflate(R.layout.temp_layout, null, false)
view
},
modifier = Modifier
.padding(32.dp)
.fillMaxWidth()
.height(200.dp)
.constrainAs(image) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
})
And you will add a temp layout like this
temp_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="@drawable/cureved_rect"
android:layout_height="match_parent">
</ImageView>
Upvotes: 3