Skip to content Skip to sidebar Skip to footer

How To Draw Path Like Canvas In Android Using Opengl Es 2?

I have tried Canvas in Android, and I can make sketch or path by moving my finger on the screen. Now, I want to do the same thing using OpenGL 2. I'm new to OpenGL programming but

Solution 1:

If you want to draw a consistent line along a path, then you're in fact trying to draw many short lines which are all connected to each other.

I think the most intuitive way of doing this, is adding each point on the path into an array of points, and then, maintaining a float buffer, where each 3 items describe a single point on the path (x,y,z). Then, for every point which is added to this vertex buffer, you should add two integers into an index buffer. If you're new to index buffers, the way it works (when you're working with lines), is it tells OpenGL which two vertexes are connected. For instance:

Say you have 3 points. Inside the Vertex buffer, you would have 9 floats - 3 points * 3 coordinates for each point. We would like the 1st point to be connected to the 2nd, and the 2nd point to be connected to the 3rd. We can do this by using an Index Buffer. In the index buffer, we will place 2 integers for every vertex connection. For connecting the 1st point to the 2nd, we will player 0 & 1 into the buffer. This says that the 1st 3 coordinates in the vertex buffer are connected to the 2nd 3 coordinates in the vertex buffer. Then, we will place 1 & 2 in the index buffer. This says that the 2nd 3 coordinates in the vertex buffer are connected to the 3rd 3 coordinates in the vertex buffer - and so on.

Vertex Buffer:
{
  0, 0, 0, // Index 01, 1, 1, // Index 12, 3, 4// Index 2
}

Index Buffer:
{
  0, 1, // Connect Index 0 to Index 11, 2// Connect Index 1 to Index 2
}

You will need to call glDrawElements rather than glDrawArrays, but the idea is the same - you only need to maintain an additional buffer for the indexes, and make sure to always update both buffers each time you add a new point.

As for the concurrent modification exception - you need to be a bit careful here. If you add a point to the array while you're iterating over the array (for example, with a "for each" style loop), then this will happen. A good solution is to surround any interaction with the point array with a synchronize block, and use the array itself as a mutex:

Adding:
synchronized(myPointArray)
{
  myPointArray.add(newPoint);
}


Iterating:
synchronized(myPointArray)
{
  for (PointF point : myPointArray)
  {
    // do stuff with the point
  }
}

This should get you started.

Post a Comment for "How To Draw Path Like Canvas In Android Using Opengl Es 2?"