我必须在SurfaceView上画一些物体在周围移动的轨迹。对象的跟踪被实现为点的LinkedList (点是SurfaceView上的一对浮动坐标)。LinkedList的动机是这样的行为
public class Trail extends LinkedList<Points> {
private static int numbOfPoints;
@Override
public boolean add(Point point) {
super.add(point);
while( this.size() > Trail.numbOfPoints ) {
super.remove();
}
return true;
}
}其中numbOfPoints是最大的跟踪点数。如果添加了一个新的点,那么将最老的点从轨迹中移除,以保持固定的路径大小。但是,当我绘制这些点时,为了使用float[] (float[]),我将使用一个点而不是一个点的LinkedList。所以我想出了一个从LinkedList到float[]的手动转换,这个转换效率很低,并且会带来一些麻烦……
因此,有一种方法可以避免使用LinkedList并将坐标直接存储到具有上述行为的float[]中?
发布于 2015-06-16 23:22:45
我认为实现这一点的最好方法是通过环形缓冲器。我真的不明白您是如何使用float[]而不是float[][]在画布上画东西的,但是您应该能够让这个解决方案使用您喜欢的任何类型:
class Trail {
private final int maxLength;
private float[] points;
private int start = 0;
private int length = 0;
private float[] buffer;
public Trail(int maxLength) {
this.maxLength = maxLength;
this.points = new float[maxLength];
this.buffer = new float[0];
}
public void add(float point) {
points[(start + length) % points.length] = point;
if (length < maxLength) {
length++;
} else {
start = (start + 1) % points.length;
}
}
public float[] getTail() {
if (buffer.length != length) { // Reusing the array if possible.
buffer = new float[length];
}
int itemsFromStartToArrayEnd = Math.min(length, points.length - start);
System.arraycopy(points, start, buffer, 0, itemsFromStartToArrayEnd);
if (start + length > maxLength) {
System.arraycopy(points, 0, buffer, itemsFromStartToArrayEnd, length - itemsFromStartToArrayEnd);
}
return buffer;
}
}https://stackoverflow.com/questions/30879645
复制相似问题