[关闭]
@cxm-2016 2016-09-20T04:39:03.000000Z 字数 1288 阅读 2689

Android:制作简易画板

android no


这里我们实现一个自定义的画板,并逐渐完善其功能。当用户在频幕上画线时,实际上依然是利用Canvas的drawLine方法绘制直线,每条直线都是上一次的点到这一次的点之间的连线。

简单版

这里我们创建一个PainterView,View的代码如下

  1. class PainterView : View {
  2. constructor(context: Context?) : super(context)
  3. constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
  4. constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
  5. private var preX = 0F
  6. private var preY = 0F
  7. private var path = Path()
  8. private var paint = Paint(Paint.DITHER_FLAG)
  9. private var cacheBitmap:Bitmap? = null
  10. private var cacheCanvas = Canvas()
  11. init {
  12. paint.color = Color.BLUE
  13. paint.style = Paint.Style.STROKE
  14. paint.strokeWidth = 2F
  15. paint.isAntiAlias = true
  16. paint.isDither = true
  17. post {
  18. cacheBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
  19. cacheCavas.setBitmap(cacheBitmap)
  20. }
  21. }
  22. override fun onTouchEvent(event: MotionEvent): Boolean {
  23. val x = event.x
  24. val y = event.y
  25. when (event.action) {
  26. MotionEvent.ACTION_DOWN -> {
  27. path.moveTo(x, y)
  28. preX = x
  29. preY = y
  30. }
  31. MotionEvent.ACTION_MOVE -> {
  32. path.quadTo(preX, preY, x, y)
  33. cacheCanvas.drawPath(path,paint)
  34. preX = x
  35. preY = y
  36. }
  37. MotionEvent.ACTION_UP -> {
  38. path.reset()
  39. }
  40. }
  41. invalidate()
  42. return true
  43. }
  44. override fun onDraw(canvas: Canvas) {
  45. canvas.drawBitmap(cacheBitmap,0F,0F,paint)
  46. }
  47. }

通过这个程序我们可以看出,每次手指在屏幕上滑动时都会记录下手指位置,然后通过invalidate()通知View进行重绘。这个View是有缺陷的,我们将View添加到布局中运行。当我们的手指滑动速度过快时,会产生如下的折点

这种问题产生的原因就是

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注