A Method of Realizing Random Doodling on ImageView in android

  • 2021-10-16 02:39:35
  • OfStack

My idea of realization:

1. Inherit the ImageView class

2. Rewrite the onTouchEvent method. In ACTION_MOVE (i.e. when moving), record the coordinates of the points passed by, and in ACTION_UP (i.e. when the finger leaves, when a line has been drawn), save the drawn lines (set of points) in a set

3. Rewrite the onDraw method and draw lines using canvas and recorded lines and dots

Maybe my 10 points are general, let's take a look at the actual code


// Representative ImageView Above 1 Point 
public class ViewPoint
{
    float x;
    float y;
}

// Denote 1 Strip line 
public class Line
{
    ArrayList<ViewPoint> points = new ArrayList<ViewPoint>(); 
}

As shown above, ViewPoint represents 1 point and Line represents 1 line

Then declare the following on the extended ImageView class:


public class HandWritingImageView extends ImageView
{
    private Paint paint;

    // The line currently being drawn 
    private Line current = new Line();
 // All the lines drawn 
    private ArrayList<Line> lines = new ArrayList<Line>(); 
}

The onTouchEvent method is then overridden


@Override
 public boolean onTouchEvent(MotionEvent event)
 { 
 // Get coordinates 
 clickX = event.getX();
 clickY = event.getY();
 
 if (event.getAction() == MotionEvent.ACTION_DOWN)
 {
  invalidate();
  
  return true;
 }
 else if (event.getAction() == MotionEvent.ACTION_MOVE) 
 {
  ViewPoint point = new ViewPoint();
  point.x = clickX;
  point.y = clickY;
  // Add a passing point when moving 
  current.points.add(point);

  invalidate();
  return true;
 }
 else if (event.getAction() == MotionEvent.ACTION_UP) 
 { 
  // Add a drawn line 
  lines.add(current);
  current = new Line();
   
  invalidate();
 }
 
 return super.onTouchEvent(event);
 }

You can see that when our finger moves, we get to save the passing point and call the invalidate method to refresh the screen (so that the onDraw method can be called, which can be seen later), add the previously drawn line to the collection when our finger leaves, and call the invalidate method

Next, look at the rewritten onDraw method, which uses the saved line information to draw lines


@Override 
 protected void onDraw(Canvas canvas) 
 { 
 super.onDraw(canvas);
 // Draw all the lines before 
 for (int i = 0; i < lineData.lines.size(); i++)
 {
  drawLine(canvas, lines.get(i));
 }
  
 // Draw the current line 
 drawLine(canvas, current);
 
 } 
 
 private void drawLine(Canvas canvas, Line line)
 {
 for (int i = 0; i < line.points.size() - 1; i++)
 {
  float x = line.points.get(i).x;
  float y = line.points.get(i).y;
  
  float nextX = line.points.get(i + 1).x;
  float nextY = line.points.get(i + 1).y;
  
  canvas.drawLine(x, y, nextX, nextY, paint);
 }
 }

In this way, you can doodle on ImageView at will, and you can also undo it by deleting the last line in lines.


Related articles: