android怎么手写展示图片
时间: 2024-01-25 18:03:39 浏览: 111
要在Android应用程序中展示手写图片,可以使用Canvas API和Bitmap类来实现。具体步骤如下:
1.在布局文件中添加一个画布View:
```
<com.example.handwriting.CanvasView
android:id="@+id/canvas"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF"
android:layout_gravity="center" />
```
2.创建一个CanvasView类,并在其中实现onDraw方法,用于绘制手写图片:
```
class CanvasView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var path = Path()
private val drawPaint = Paint()
private val canvasPaint = Paint(Paint.DITHER_FLAG)
private lateinit var canvasBitmap: Bitmap
private lateinit var drawCanvas: Canvas
init {
drawPaint.apply {
color = Color.BLACK
isAntiAlias = true
strokeWidth = 20f
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
}
}
override fun onDraw(canvas: Canvas) {
canvas.drawBitmap(canvasBitmap, 0f, 0f, canvasPaint)
canvas.drawPath(path, drawPaint)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val touchX = event.x
val touchY = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> {
path.moveTo(touchX, touchY)
}
MotionEvent.ACTION_MOVE -> {
path.lineTo(touchX, touchY)
}
MotionEvent.ACTION_UP -> {
drawCanvas.drawPath(path, drawPaint)
path.reset()
}
else -> return false
}
invalidate()
return true
}
fun init(height: Int, width: Int) {
canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
drawCanvas = Canvas(canvasBitmap)
}
}
```
3.在Activity中获取CanvasView,并设置其高度和宽度:
```
val canvasView = findViewById(R.id.canvas) as CanvasView
canvasView.init(displayMetrics.heightPixels, displayMetrics.widthPixels)
```
4.保存手写的图片,并展示到ImageView中:
```
val image = canvasView.drawingCache
val imageView = findViewById(R.id.image_view) as ImageView
imageView.setImageBitmap(image)
```