【发布时间】:2021-05-21 05:12:20
【问题描述】:
我正在尝试创建一个简单的应用程序,我可以在其中在已转换为位图的 pdf 页面上绘制签名。 我成功实现了 PDF 功能,但在我的应用中实现 SignaturePad 功能时遇到了问题。
当我在我的 SignaturePad 视图上绘图时,它会准确地绘制我在屏幕上拖动的位置。 Image: Signature on the drawing pad
但是,当我显示生成的位图时,签名会显得更大且位置偏离。 Image: Signature after displaying the resulting bitmap
我尝试了多种解决方案来解决密切相关的问题,例如:
- https://stackoverflow.com/a/11437439/12209523
- https://stackoverflow.com/a/4013780/12209523
- https://stackoverflow.com/a/5891607/12209523
但它们都不起作用。
我有使用 android.graphics 库的 0(零)经验,所以我对自己做错了什么一无所知。非常感谢任何帮助或建议!
我的 SignaturePad 类:
class SignaturePad(context: Context, attrs: AttributeSet): androidx.appcompat.widget.AppCompatImageView(context, attrs) {
companion object{
// To use for logging
private const val TAG = "SignaturePad"
}
// this attribute store the original immutable bitmap
private var originalBitmap: Bitmap? = null
// this attribute store a mutable copy of the original bitmap
private var mBitmap:Bitmap? = null
private var path = Path()
private val brush = Paint(Paint.ANTI_ALIAS_FLAG)
private var mCanvas: Canvas = Canvas()
init{
brush.isAntiAlias = true
brush.color = Color.BLACK
brush.style = Paint.Style.STROKE
brush.strokeCap = Paint.Cap.ROUND
brush.strokeJoin = Paint.Join.ROUND
brush.strokeWidth = 5f
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
event?.let{
val pointX:Float = it.x
val pointY:Float = it.y
when(it.action){
MotionEvent.ACTION_DOWN -> {
path.moveTo(pointX, pointY)
return true
}
MotionEvent.ACTION_MOVE -> {
path.lineTo(pointX, pointY)
}
MotionEvent.ACTION_UP -> {
// do nothing
}
else -> return false
}
postInvalidate()
return false
}
return super.onTouchEvent(event)
}
// function is overridden so i can store the bitmap into an attribute and use it on the canvas
override fun setImageBitmap(bm: Bitmap?) {
bm?.let{
originalBitmap = bm
mBitmap= originalBitmap!!.copy(Bitmap.Config.ARGB_8888, true)
mCanvas = Canvas()
mCanvas.setBitmap(mBitmap!!)
}
super.setImageBitmap(bm)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
if (mBitmap == null) {
Log.e(TAG,"Bitmap is null!")
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
}
mCanvas = Canvas()
mCanvas.setBitmap(mBitmap)
mCanvas.drawColor(Color.TRANSPARENT)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.let{
it.drawPath(path, brush)
mCanvas.drawPath(path, brush)
}
}
fun getCanvas():Canvas?{
return mCanvas
}
fun getBitmap():Bitmap?{
return mBitmap
}
}
我在 Activity 上的自定义 SignaturePad 小部件:
<com.fca.signpdf.view.SignaturePad
android:id="@+id/signaturepad"
android:background="@color/white"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/buttonbar"
android:layout_width="match_parent"
android:layout_height="0dp"
android:minHeight="300dp"
android:scaleType="fitCenter"/>
【问题讨论】:
标签: android kotlin canvas bitmap signature