每当我尝试更改我的绘画属性(厚度或颜色)时,它会更改已经在画布上的现有绘画(android)(java)

时间:2015-12-06 00:40:14

标签: java android android-canvas paint android-bitmap

我试图创建一个简单的绘图应用程序,允许您在画布上绘图,并且您可以更改它的颜色和厚度。出现的问题是,每次我尝试更改颜料或颜色时,它都会改变画布上现有的颜色。我理解为什么它不起作用,但我不知道如何解决它以及问题究竟在哪里。

CanvasView类

package samkough.com.painter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;

public class CanvasView extends View
{
    /*
    * When the user touches the screen and moves their finger to draw,
    * we will use a Path to trace their drawing action on the canvas.
    * Both the canvas and the drawing on top of it are represented by Paint
    * objects. The initial paint color corresponds to the first color
    * in the palette we created last time, which will be initially selected
    * when the app launches. Finally we declare variables for the canvas
    * and bitmap - the user paths drawn with drawPaint will be drawn onto
    * the canvas, which is drawn with canvasPaint.
    * */
    //drawing paint
    private Paint paint = new Paint();
    // canvas paint
    private Paint canvasPaint = new Paint();
    //drawing path
    private Path path = new Path();
    // canvas
    private Canvas canvas = new Canvas();
    //canvas bitmap
    private Bitmap canvasBitmap;
    // brush size and pixel size
    private float brushSize, pixelAmount;

    public CanvasView(Context context, AttributeSet attrs)
    {
        // Setting the anti-alias, stroke join and cap styles will make the user's drawings appear smoother.
        super(context, attrs);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(canvasBitmap);
    }

    @Override
    protected void onDraw(Canvas drawCanvas)
    {
        drawCanvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
        drawCanvas.drawPath(path, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e)
    {
        // get the coords of the touch event
        float eventX = e.getX();
        float eventY = e.getY();

        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // set a new starting point
                path.moveTo(eventX, eventY);
                path.reset();
                path.moveTo(eventX, eventY);
                return true;
            case MotionEvent.ACTION_MOVE:
                // connect the points
                path.lineTo(eventX, eventY);
                break;
            default:
                return false;
        }

        // makes you view repaint and call ondraw
        invalidate();
        return true;
    }

    public void clearCanvas()
    {
        path.reset();
        invalidate();
    }

    public void setStrokeWidth(float f)
    {
        pixelAmount = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, f, getResources().getDisplayMetrics());
        brushSize = pixelAmount;

        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(brushSize);
        invalidate();
    }

    public void setColor(int p)
    {
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setColor(p);
        invalidate();
    }
}

MainActivity Class

package samkough.com.painter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import com.samkough.painter.R;

public class MainActivity extends Activity {

    private CanvasView canvasView;
    private int orange;
    private int purple;
    private float strokeWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        canvasView = (CanvasView) findViewById(R.id.canvasView);
        orange = Color.rgb(250, 128, 0);
        purple = Color.rgb(128, 0, 128);
        strokeWidth = 0;

        // REGULAR BUTTONS: save, about, reset
        Button saveB = (Button) findViewById(R.id.saveButton);
        Button aboutB = (Button) findViewById(R.id.aboutButton);
        Button resetB = (Button) findViewById(R.id.resetButton);

        // IMAGE BUTTONS: red, blue, green, yellow, black, purple, orange, erase, brush thickness plus, brush thickness minus
        ImageButton redIb = (ImageButton) findViewById(R.id.redButton);
        ImageButton blueIb = (ImageButton) findViewById(R.id.blueButton);
        ImageButton greenIb = (ImageButton) findViewById(R.id.greenButton);
        ImageButton yellowIb = (ImageButton) findViewById(R.id.yellowButton);
        ImageButton blackIb = (ImageButton) findViewById(R.id.blackButton);
        ImageButton purpleIb = (ImageButton) findViewById(R.id.purpleButton);
        ImageButton orangeIb = (ImageButton) findViewById(R.id.orangeButton);
        ImageButton eraseIb = (ImageButton) findViewById(R.id.eraseButton);
        ImageButton plusIb = (ImageButton) findViewById(R.id.plusButton);
        ImageButton minusIb = (ImageButton) findViewById(R.id.minusButton);

        minusIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                strokeWidth -= 2;
                canvasView.setStrokeWidth(strokeWidth);
            }
        });

        plusIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                strokeWidth += 2;
                canvasView.setStrokeWidth(strokeWidth);
            }
        });

        eraseIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(Color.TRANSPARENT);
            }
        });

        orangeIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(orange);
            }
        });

        purpleIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(purple);
            }
        });

        blackIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(Color.BLACK);
            }
        });

        yellowIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(Color.YELLOW);
            }
        });

        greenIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(Color.GREEN);
            }
        });

        blueIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(Color.BLUE);
            }
        });

        redIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.setColor(Color.RED);
            }
        });

        saveB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        aboutB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), AboutActivity.class);

                startActivity(intent);
            }
        });

        resetB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvasView.clearCanvas();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:2)

CanvasView.java中,此行

private Paint paint = new Paint();

为整个类声明一个paint对象,并且这行

private Path path = new Path();

为整个类声明一个路径对象。

调用onDraw时,整个画布区域正在重绘。这意味着

drawCanvas.drawPath(path, paint);

正在绘制自创建活动以来添加的整个path,其中包含paint的当前值。

解决此问题的一种方法是拥有Path个对象列表和Paint个对象列表。路径列表的第一个元素将存储绘制的第一个路径 - 比如,绘制所有内容直到它们更改绘制的点。绘制列表的第一个元素将存储使用的相应绘制。每当用户更改绘画并开始绘画时,您都需要创建一个新的Path对象,并将其和新的Paint对象添加到列表中。

一旦你有了路径列表和绘制它们的颜料,你就可以在onDraw中做到这样的事情:

for (int i = 0; i < paths.size(); i++) {
  Path path = paths.get(i);
  Paint paint = paints.get(i);
  drawCanvas.drawPath(path, paint);
} 

答案 1 :(得分:2)

您已创建canvas,但您没有使用它来绘制任何内容。基本上,行drawCanvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);没有做任何事情。

您需要做的是在path上绘制canvas。然后使用canvasBitmap绘制drawCanvas。这样,您可以维护单个path和单个paint,而不是多个。{/ p>

@Override
protected void onDraw(Canvas drawCanvas)
{
    canvas.drawPath(path, paint);
    drawCanvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
}

当您执行上述操作时,每次用户绘制新路径时,canvasBitmap都会保留其中的所有旧路径。因此,每次调用onDraw时,只会绘制新的path

永远记住:创建多个 PAINT对象是一种不好的做法。尝试尽可能多地重用Paint对象。