Search code examples
androidarraysdrawingsampling

Sampling a Drawn Line into an Array


I would like "sample" a line hand-drawn by a user on the android screen into an array. The x-coordinates would be equidistant and would very likely be the indices of the 1D array.

To give an example of what I mean, if the user draws an approximate sine wave, I want to create an array that can translate that approximate sine wave to yet another graph, or be used in audio synthesis.

I have a basic idea as to an approach, start with an array:

float samples[] = new float[100] // or some other arbitrary number

Then an ontouch method:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        if(event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE){
            // assume we translate x into relative index from 0-99 at this point
            if(!xHasPoint(x, samples)){
                drawNewPoint();
                samples[x] = y;
            }
            invalidate();
            return true;
        }
        else{
            invalidate();
            return false;
        }
    }

private static boolean xHasPoint(float x, float[] a){
    if(a[x] == !null){
         return true;
    }
    else{
         return false;
    }
}

So my question is, can you suggest a better approach to this problem? I foresee having to extrapolate a lot data... looping through the array at the end and assigning null indices mean values from the nearest non-null values, that sort of thing.

On the other hand, if this doesn't seem wrong, am I missing any important big-picture considerations?


Solution

  • The only problem is, that once your array is full, you can't keep adding more points. I would suggest, you go with a growable data structure.

    Say for example, if it's an ArrayList, you can keep adding any number of points(theoretically).

    I don't really understand the method hasPoints. Ideally, while drawing itself, you should be simultaneously sampling, and interpolating, and also may be, smoothing the curves.

    Update: Yeah, if that is the case, then you could only try and register a point only when it has moved, say more than 4 pixels, and then somehow interpolate and draw the curve by smoothing it between the previous and the next point. And also, you would need to capture y-points as well I guess.