@cxm-2016
2016-09-20T04:39:03.000000Z
字数 1288
阅读 3191
android no
这里我们实现一个自定义的画板,并逐渐完善其功能。当用户在频幕上画线时,实际上依然是利用Canvas的drawLine方法绘制直线,每条直线都是上一次的点到这一次的点之间的连线。
这里我们创建一个PainterView,View的代码如下
class PainterView : View {constructor(context: Context?) : super(context)constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)private var preX = 0Fprivate var preY = 0Fprivate var path = Path()private var paint = Paint(Paint.DITHER_FLAG)private var cacheBitmap:Bitmap? = nullprivate var cacheCanvas = Canvas()init {paint.color = Color.BLUEpaint.style = Paint.Style.STROKEpaint.strokeWidth = 2Fpaint.isAntiAlias = truepaint.isDither = truepost {cacheBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)cacheCavas.setBitmap(cacheBitmap)}}override fun onTouchEvent(event: MotionEvent): Boolean {val x = event.xval y = event.ywhen (event.action) {MotionEvent.ACTION_DOWN -> {path.moveTo(x, y)preX = xpreY = y}MotionEvent.ACTION_MOVE -> {path.quadTo(preX, preY, x, y)cacheCanvas.drawPath(path,paint)preX = xpreY = y}MotionEvent.ACTION_UP -> {path.reset()}}invalidate()return true}override fun onDraw(canvas: Canvas) {canvas.drawBitmap(cacheBitmap,0F,0F,paint)}}
通过这个程序我们可以看出,每次手指在屏幕上滑动时都会记录下手指位置,然后通过invalidate()通知View进行重绘。这个View是有缺陷的,我们将View添加到布局中运行。当我们的手指滑动速度过快时,会产生如下的折点
这种问题产生的原因就是
