https://developer.android.com/develop/u ... -to-bitmap
Это работает нормально, но Мне нужно, чтобы конечный файл имел закругленные углы на прозрачном фоне. Что я пробовал:
- Вырезка с помощью GraphicsLayer. Это делает углы скругленными, но фон черным.
- Изменение растрового изображения, полученного из GraphicsLayer, кажется невозможным, поскольку оно имеет Config.HARDWARE. Я не нашел способа сделать его изменяемым или скопировать в другое растровое изображение. Я даже цвет пикселей проверить не могу - все эти операции приводят к IllegalStateException.
Вот мой код:
@Composable
fun SomeComposable() {
val coroutineScope = rememberCoroutineScope()
val graphicsLayer = rememberGraphicsLayer()
val context = LocalContext.current
val radius = 16.dp.toPx(context)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.drawWithContent {
graphicsLayer.clipWith(radius, this@drawWithContent.size)
// call record to capture the content in the graphics layer
graphicsLayer.record {
// draw the contents of the composable into the graphics layer
this@drawWithContent.drawContent()
}
// draw the graphics layer on the visible canvas
drawLayer(graphicsLayer)
}
.background(Color.Red)
) {
Button(onClick = {
coroutineScope.launch {
val bitmap = graphicsLayer.toImageBitmap().asAndroidBitmap()
context.shareWithChooser(bitmap)
}
}) {
Text(text = "Share")
}
}
}
private fun GraphicsLayer.clipWith(radius: Float, size: Size) {
clip = true
setOutline(
Outline.Rounded(
RoundRect(
0f,
0f,
size.width,
size.height,
cornerRadius = CornerRadius(radius, radius)
)
)
)
}
suspend fun Context.shareWithChooser(bitmap: Bitmap) {
withContext(Dispatchers.IO) {
val file = File.createTempFile("IMG_", ".jpg", filesDir)
val stream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
stream.flush()
stream.close()
withContext(Dispatchers.Main) {
val imageUri =
FileProvider.getUriForFile(this@shareWithChooser, BuildConfig.APPLICATION_ID, file)
val shareIntent = Intent(Intent.ACTION_SEND).apply {
type = "image/jpeg"
flags =
Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
data = imageUri
putExtra(Intent.EXTRA_STREAM, imageUri)
}
val chooser = Intent.createChooser(shareIntent, "")
startActivity(chooser)
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ck-compose
Мобильная версия