元の形が長方形の画像を正円に切り取る際に、地味に調べるのに時間がかかったのでメモしておこうと思います。
[目次]
環境
- compose_version = '1.0.1' - targetSdk 31 - kotlinCompilerVersion '1.5.21'
うまくいかなかった例
Modifier.clip()
に対し、以下のように指定しましたが上手くいきませんでした。
Modifier の情報を他にも追加してみましたが、効果的なものはありませんでした。
@Composable fun ImageTest() { Image( painter = painterResource(R.drawable.test), modifier = Modifier .size(300.dp) .clip(CircleShape), contentDescription = "test image" ) }
その時の写真
改善策
以下のようにcontentScale
を指定してあげます。
他にもいろいろな ContentScale のパラメータはあるようです。
@Composable fun ImageTest() { Image( painter = painterResource(R.drawable.test), modifier = Modifier .size(300.dp) .clip(CircleShape), contentDescription = "test image", // crop the image if it's not a square contentScale = ContentScale.Crop, ) }
ただしこのままでは長辺に対し、常に中央で写真が切り取られてしまいます。
上部分を用いて正円を作る
正円を切り取る部分を中央からずらしたい場合、以下のようにalignment
を指定します。
@Composable fun ImageTest() { Image( painter = painterResource(R.drawable.test), modifier = Modifier .size(300.dp) .clip(CircleShape), contentDescription = "test image", // crop the image if it's not a square contentScale = ContentScale.Crop, alignment = Alignment.TopStart ) }
おわりに
今回は、長方形の写真をうまく正円に切り取る方法について紹介しました。
今後も Jetpack Compose を使った開発を続けていきたいと思っています。