package de.hems.trafficsim; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; import java.util.ConcurrentModificationException; import java.util.List; public class TimeRecordView extends View { protected Paint paint; protected Track track; protected int pixelPerVehicle; protected float tooShortPerTrackLength; protected int historyLength; public TimeRecordView(Context context, Track track, int historyLength) { super(context); this.track = track; this.paint = new Paint(); this.historyLength = historyLength; paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.FILL_AND_STROKE); this.setBackgroundColor(Color.BLACK); this.pixelPerVehicle = (int) (this.getWidth() / this.track.getTrackLength()); this.tooShortPerTrackLength = (this.getWidth() - this.pixelPerVehicle*this.track.getTrackLength())/this.track.getTrackLength(); } public void setTrack(Track track) { this.track = track; } protected int getColor(float curVelocity, float maxVelocity) { float perc = curVelocity / maxVelocity; perc = 1 - perc; if (perc <= 0.5) { int red = ((int) (2*perc*0xFF)) << 16; int green = ((int)0xFF) << 8; int blue = 0; return 0xff000000 | red | green | blue; } else { int red = ((int)(0xFF)) << 16; int green = ((int)(0xFF-0xFF*(perc-0.5)*2)) << 8; int blue = 0; return 0xff000000 | red | green | blue; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, 10*50); setMeasuredDimension(widthMeasureSpec, 10*50); this.pixelPerVehicle = (int) (this.getWidth() / this.track.getTrackLength()); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); this.pixelPerVehicle = (int) (this.getWidth() / this.track.getTrackLength()); this.tooShortPerTrackLength = (this.getWidth() - this.pixelPerVehicle*this.track.getTrackLength())/this.track.getTrackLength(); } @Override protected void onDraw(Canvas canvas) { int y = 0; List> stepList = this.track.getVtrList(); for (int curStepIdx = this.historyLength-1; curStepIdx >= 0 && stepList.size() >= curStepIdx; curStepIdx--) { try { try { track.getListSemaphore().acquire(); } catch (InterruptedException ex) { return; } List step = stepList.get(curStepIdx); int i = 0; for (VehicleTimeRecord r : step) { int left = (int) (this.pixelPerVehicle * r.getPosition()); int compensate = Math.round(r.getPosition()*this.tooShortPerTrackLength); this.paint.setColor(getColor(r.getVelocity(), r.getMaxVelocity())); canvas.drawRect(left+compensate, y, left + this.pixelPerVehicle - 1+compensate, y + 10, this.paint); i++; } track.getListSemaphore().release(); y += 10; } catch (ConcurrentModificationException ex) { System.out.println("Concurrent Exception occured, skipping record"); y += 10; continue; } } } }