You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio(Kotlin)绘画App画笔粗细修改异常问题求助

解决方案:分离已绘制路径与当前画笔参数

问题根源在于你可能复用了同一个Paint对象绘制所有路径,修改画笔属性后,重绘时所有路径都会使用新的参数。要解决这个问题,需要为每条绘制的路径绑定独立的画笔属性(粗细、颜色等),只让新参数作用于即将绘制的内容。

步骤1:创建路径-属性绑定的数据类

创建一个数据类,用来保存单条路径对应的画笔参数:

data class DrawingPath(
    val path: Path,
    val strokeWidth: Float,
    val color: Int
)

步骤2:重构PaintView的核心逻辑

修改自定义PaintView,用列表保存所有已完成的路径及其属性,同时维护当前画笔的参数(仅用于新绘制):

class PaintView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    // 存储所有已完成的绘制路径与对应属性
    private val completedDrawings = mutableListOf<DrawingPath>()
    // 当前画笔参数(仅控制即将绘制的内容)
    private var currentStrokeWidth = 5f
    private var currentColor = Color.BLACK
    // 正在绘制中的临时路径
    private val tempPath = Path()
    // 复用的Paint对象(重绘时动态设置参数)
    private val paint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.ROUND
        strokeCap = Paint.Cap.ROUND
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                tempPath.moveTo(x, y)
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                tempPath.lineTo(x, y)
                invalidate()
            }
            MotionEvent.ACTION_UP -> {
                // 完成绘制,将临时路径与当前参数绑定后存入列表
                completedDrawings.add(DrawingPath(Path(tempPath), currentStrokeWidth, currentColor))
                tempPath.reset()
                invalidate()
            }
        }
        return super.onTouchEvent(event)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 绘制所有已完成的路径,每条路径用自己的参数
        completedDrawings.forEach { drawing ->
            paint.strokeWidth = drawing.strokeWidth
            paint.color = drawing.color
            canvas.drawPath(drawing.path, paint)
        }
        // 绘制正在进行中的临时路径,用当前画笔参数
        paint.strokeWidth = currentStrokeWidth
        paint.color = currentColor
        canvas.drawPath(tempPath, paint)
    }

    // 对外提供设置当前画笔参数的方法
    fun updateStrokeWidth(width: Float) {
        currentStrokeWidth = width
    }

    fun updateColor(color: Int) {
        currentColor = color
    }
}

步骤3:在外部页面调用更新方法

在Collab主页面或ColourPicker页面,直接调用PaintView的更新方法即可,不会影响已绘制内容:

// 示例:滑块调整画笔粗细(Collab页面)
strokeWidthSlider.addOnChangeListener { _, selectedWidth, _ ->
    paintView.updateStrokeWidth(selectedWidth)
}

// 示例:选择颜色后更新(ColourPicker页面)
fun onColorConfirmed(selectedColor: Int) {
    paintView.updateColor(selectedColor)
}

关键说明

  • 已完成的路径会和绘制时的画笔参数绑定保存,重绘时每条路径使用自己的参数,不受后续画笔设置影响。
  • 临时路径(手指未抬起时的绘制)使用当前画笔参数,确保实时预览效果正常。

内容的提问来源于stack exchange,提问作者Cruz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:36:58