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

Android Studio绘图APP:画笔大小调整影响已绘制内容的问题

问题原因

你当前的实现只记录了每个绘制路径(Path)对应的颜色,但没有保存每个路径绘制时的画笔宽度。在onDraw方法中,你复用同一个Paint对象绘制所有历史路径,每次修改Paint的strokeWidth后,所有旧路径都会使用新的画笔宽度重新绘制,这就导致了已绘制内容的尺寸跟着变化。

解决方案

需要为每个路径单独保存对应的画笔宽度,就像你保存颜色一样。具体修改步骤如下:

1. 添加存储画笔宽度的列表

在CanvasView类中添加两个变量:一个记录所有历史路径的画笔宽度,一个记录当前正在使用的画笔宽度:

// 记录每个路径对应的画笔宽度
private List<Float> strokeWidths = new ArrayList<>();
// 当前使用的画笔宽度,替代直接修改全局Paint的strokeWidth
private float currentStrokeWidth = 4f;

2. 初始化时调整Paint设置

在构造方法中,用currentStrokeWidth初始化Paint的宽度:

public CanvasView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    path = new Path();
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    // 改用currentStrokeWidth初始化画笔宽度
    paint.setStrokeWidth(currentStrokeWidth);
}

3. 修改画笔大小调整方法

调整increasePenSize和decreasePenSize,只修改currentStrokeWidth,同时增加最小宽度限制避免异常:

public void increasePenSize() {
    currentStrokeWidth += 2f;
}

public void decreasePenSize() {
    currentStrokeWidth -= 2f;
    // 限制最小宽度,避免变成0或负数
    if (currentStrokeWidth < 1f) {
        currentStrokeWidth = 1f;
    }
}

4. 开始绘制时保存当前画笔宽度

在startTouch方法中,把当前的currentStrokeWidth添加到宽度列表:

public void startTouch(float x, float y)
{
    path = new Path();
    path.moveTo(x, y);
    mX = x;
    mY = y;

    paths.add(path);
    colors.add(currentColor);
    // 保存当前画笔宽度到列表
    strokeWidths.add(currentStrokeWidth);
}

5. 修改onDraw方法,使用对应宽度绘制历史路径

在onDraw循环中,为每个路径设置对应的颜色和画笔宽度:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    for (int i = 0; i < paths.size(); i++) {
        paint.setColor(colors.get(i));
        // 设置当前路径对应的画笔宽度
        paint.setStrokeWidth(strokeWidths.get(i));
        canvas.drawPath(paths.get(i), paint);
    }
}

6. 清空画布时同步清空宽度列表

修改clearCanvas方法,清空strokeWidths:

public void clearCanvas()
{
    paths.clear();
    colors.clear();
    // 同步清空宽度列表
    strokeWidths.clear();
    bitmap.eraseColor(Color.TRANSPARENT);
    invalidate();
}

这样修改后,每个历史路径都会使用绘制时的画笔宽度渲染,调整画笔大小只会影响后续新绘制的内容,旧内容不会再改变尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:24:54