我在SurfaceView中创建了一个称为的覆盖方法draw 。我想看一下我在SurfaceView中设置的绘画,但是当我触摸屏幕并试图画一条线时,什么都没有显示。我应该怎么做才能使这项工作?
private var mPaint: Paint
private val mPaths: ArrayList<Path> = ArrayList<Path>()
private val mEraserPath: Path = Path()
init {
mPaint = Paint()
mPaint.isAntiAlias = true
mPaint.isDither = true
mPaint.style = Paint.Style.STROKE
mPaint.strokeJoin = Paint.Join.ROUND
mPaint.strokeCap = Paint.Cap.ROUND
mPaint.strokeWidth = 3f
mPaint.alpha = 255
mPaint.color = android.graphics.Color.BLACK
mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
override fun draw(canvas: Canvas) {
canvas.drawPaint(mPaint)
val action: EditAction? = this.getEditAction()
for (path: Path in mPaths) {
when (action) {
EditAction.COLOR -> {
setPaintColor(this.getStrokeColor()) // android.graphics.Color.BLACK
setPaintSize(this.getStrokeSize()) // 5f
canvas.drawPath(path, mPaint)
}
EditAction.SIZE -> {
setPaintColor(this.getStrokeColor()) // android.graphics.Color.BLACK
setPaintSize(this.getStrokeSize()) // 5f
canvas.drawPath(path, mPaint)
}
EditAction.ERASER -> {
}
}
}
canvas.drawPath(mEraserPath, mPaint)
super.draw(canvas)
}
最佳答案
如下所示,不要使用draw
,而要使用SurfaceHolder.Callback
函数。我有黑人
class SlowSurfaceView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback {
private var mPaint: Paint = Paint()
init {
holder.addCallback(this)
mPaint.isAntiAlias = true
mPaint.isDither = true
mPaint.style = Paint.Style.STROKE
mPaint.strokeJoin = Paint.Join.ROUND
mPaint.strokeCap = Paint.Cap.ROUND
mPaint.strokeWidth = 3f
mPaint.alpha = 255
mPaint.color = android.graphics.Color.RED
mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
// Do nothing for now
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
}
override fun surfaceCreated(holder: SurfaceHolder) {
if (isAttachedToWindow) {
val canvas = holder.lockCanvas()
canvas?.let {
it.drawRect(Rect(100, 100, 200, 200), mPaint)
holder.unlockCanvasAndPost(it)
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val desiredWidth = suggestedMinimumWidth + paddingLeft + paddingRight
val desiredHeight = suggestedMinimumHeight + paddingTop + paddingBottom
setMeasuredDimension(View.resolveSize(desiredWidth, widthMeasureSpec),
View.resolveSize(desiredHeight, heightMeasureSpec))
}
}
参考上面的修改代码,希望您应该得到想要的。