Scrolling chart, code fragment written using the apache commons collection CircularFifoBuffer implementation.
Each refresh redraws the whole screen, giving the illusion of a scrolling chart without having to translate the canvas.
Each refresh redraws the whole screen, giving the illusion of a scrolling chart without having to translate the canvas.
import org.apache.commons.collections15.buffer.CircularFifoBuffer;
.....
private CircularFifoBuffer<Sample> mLocalBuffer;
protected Runnable serviceConsumer = new Runnable() {
@Override
public void run() {
if (!isStarted)
return;
synchronized (mLocalBuffer) {
// se ha raccolto almeno un valore
if (mService != null && mService.currentSample > 0 && !isScrolled) {
mScrollOffset = mService.currentSample;
Sample sample = mService.getSampleValue(mScrollOffset);
mLocalBuffer.add(sample);
drawSamples();
mReqNum++;
}
}
handler.postDelayed(this, mUpdateSpeed);
}
};
.....
protected void drawSamples() {
Canvas c = new Canvas(mBitmap);
c.drawColor(Color.BLACK);
drawAxis();
Paint paint = new Paint();
if (isScrolled)
paint.setColor(Color.GRAY);
else
paint.setColor(Color.GREEN);
int lastX = 0;
synchronized (mLocalBuffer) {
for (Sample sample : mLocalBuffer) {
float newY = mRect.centerY() + mScaleY
* (sample.values[SensorManager.DATA_Z] - SensorManager.STANDARD_GRAVITY);
int newX = (lastX + mSpeed);
c.drawLine(lastX, (lastX == 0 ? newY : mLastY), newX, newY, paint);
mLastY = newY;
lastX = newX;
}
}
invalidate();
}
protected void drawAxis() {
Paint paint = new Paint();
paint.setColor(Color.WHITE);
Canvas c = new Canvas(mBitmap);
c.drawLine(mRectF.left, mRectF.centerY(), mRectF.right, mRectF.centerY(), paint);
c.drawLine(mRectF.centerX(), mRectF.top, mRectF.centerX(), mRectF.bottom, paint);
}
.....
nice code
ReplyDelete