Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Do not create new canvas for each color, rather create new paths.</p> </blockquote> <p>Create <code>Path</code>'s for every new time the user touches the canvas and theoretically draws something. Store that new path along with its color and in the <code>onDraw</code> method iterate over the path structure and draw each of the paths with its saved color:</p> <pre><code>// this will hold the data of each path the user draws class DrawnItem { int color = Color.GREEN; // default values Path line = new Path(); } Paint paint; int mCurrentColor = Color.GREEN; // start with green ArrayList&lt;DrawnItem&gt; mDrawings = new ArrayList&lt;DrawnItem&gt;(); // in the onDraw method: protected void onDraw(Canvas canvas) { final int count = mDrawings.size(); for (int i = 0; i &lt; count; i++) { final DrawnItem item = mDrawings.get(i); paint.setColor(item.color); canvas.drawPath(item.line, paint); } paint.setColor(mCurrentColor); canvas.drawCircle(x, y, 10, paint); } private DrawnItem mCurrentItem = null; // and in the onTouch method: public boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: // the user started a new drawing so build a new DrawnItem mCurrentItem = new DrawnItem(); mCurrentitem.color= mCurrentColor; mDrawings.add(mCurrentItem); // use the item.line to setup the Path with the x and y values // .... invalidate(); break; case MotionEvent.ACTION_MOVE: x = event.getX(); y = event.getY(); mCurrentItem.line.lineTo(x, y); invalidate(); break; case MotionEvent.ACTION_UP: mCurrentItem.line.lineTo(event.getX(), event.getY()); mCurrentItem = null; invalidate(); break; case MotionEvent.ACTION_CANCEL: mCurrentItem = null; // this drawing session was canceled so this DrawnItem is now closed break; default: break; </code></pre> <p>Now, in your dialog, the only thing you need to do is to update the <code>mCurrentColor</code> of the custom view to point of the chosen color and from that point on the path will be drawn with the dedicated color. If the user switches the color to a previous stored color then the path corresponding for that color will be selected.</p> <p>Code for saving the view as a <code>Bitmap</code> in the doInBackground():</p> <pre><code>Bitmap bitmap = Bitmap.createBitmap(layout.getWidth(), layout.getHeight(), Bitmap.Config. RGB_565); Canvas canvas = new Canvas(bitmap); layout.draw(canvas); </code></pre> <blockquote> <p>Clear the entire canvas if ERASE button is pressed</p> </blockquote> <p>Clear the previous path structure and call <code>invalidate()</code> on your custom view:</p> <pre><code>mDrawings.clear(); customView.invalidate(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload