解决jetpack compose 手绘图形或者签名,并生成图片
val points = remember { mutableStateListOf<MoveObj>() }
var updatehadinit by remember { mutableStateOf(false) }
var needSaveBmp by remember { mutableStateOf(false) }
val savebitmap by rememberUpdatedState(needSaveBmp)
AndroidView(factory = { ctx ->
FrameLayout(ctx).apply {
/*layoutParams = ViewGroup.LayoutParams(
ScreenUtil.dp2px(ScreenUtil.mainViewWidthDp) .toInt(),
ScreenUtil.dp2px(h).toInt())*/
var composeView = ComposeView(ctx).apply {
setContent {
Canvas(modifier = Modifier
.fillMaxSize()
.background(Color(0x22000000))
) {
drawPath(path = Path().apply {
points.forEachIndexed { i, point ->
if (point.isStart == 1)
moveTo(point.x, point.y)
else
lineTo(point.x, point.y)
}
},
color = Color.Black, style = Stroke(10f))
}
}
}
addView(
composeView, ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT))
}
},
modifier = Modifier
.fillMaxWidth()
.height(h.dp).pointerInput(Unit) {
detectDragGestures(
onDragStart = { offset ->
val move: com.jp.kldc.ui.Data.MoveObj =
com.jp.kldc.ui.Data.MoveObj(
x = offset.x,
y = offset.y,
isStart = 1
)
if (move.y >= 0 && move.y <= hpx) {
points.add(move)
}
}) { change, _ ->
val move: com.jp.kldc.ui.Data.MoveObj = com.jp.kldc.ui.Data.MoveObj(
x = change.position.x, y = change.position.y, isStart = 0
)
if (move.y >= 0 && move.y <= hpx)
points.add(move)
}
}
,
update = {
if(updatehadinit == false)
{
it.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
it.layout(0, 0, it.measuredWidth, it.measuredHeight)
updatehadinit = true
}
if(savebitmap )
{
// Create a Bitmap and draw the ComposeView onto it
val bitmap = Bitmap.createBitmap(
it.measuredWidth,
it.measuredHeight,
Bitmap.Config.ARGB_8888
)
val canvas = android.graphics.Canvas(bitmap)
it.draw(canvas)
//bitmap生成 在这里进行处理,展示或者发送到服务器
}
})
needSaveBmp = false
}
}
)
不能在Canvas的modifier中处理pointerInput事件,否则如果Canvas处于可以滑动组件内时,接收不到上下滑动的事件。
needSaveBmp = true 会截图