I was trying to learn how to use SurfaceView, since I need to use it in a future project. I read that if I need to update the UI quickly, it is preferable to use SurfaceView with the help of a thread.
The purpose of my code is to be able to print on a bitmap, the pattern of a 'B',here is the code:
public void testTransition(Canvas canvas) {
if (canvas != null) {
canvas.drawColor(Color.BLACK);
Log.i("Thread", "Running...");
for (int y = 0; y < 8; y++) {
if (test[y] == 1) {
canvas.drawBitmap(ledBitMap, (x - diameterLeds) / 2, diameterLeds * y, paint);
}
}
canvas.drawColor(Color.BLACK);
delay(1000);
for (int y=0; y<8; y++){
if(test[y + 8] == 1)
canvas.drawBitmap(ledBitMap, (x - diameterLeds) / 2,diameterLeds * y, paint);
}
canvas.drawColor(Color.BLACK);
//ledThread.delay(1000);
for (int y=0; y<8; y++){
if(test[y + 16] == 1)
canvas.drawBitmap(ledBitMap, (x- diameterLeds) / 2,diameterLeds * y, paint);
}
canvas.drawColor(Color.BLACK);
//ledThread.delay(1000);
for (int y=0; y<8; y++){
if(test[y + 24] == 1)
canvas.drawBitmap(ledBitMap, (x - diameterLeds) / 2,diameterLeds * y, paint);
}
canvas.drawColor(Color.BLACK);
//ledThread.delay(1000);
for (int y=0; y<8; y++){
if(test[y + 32] == 1)
canvas.drawBitmap(ledBitMap, (x - diameterLeds) / 2,diameterLeds * y, paint);
}
//canvas.drawColor(Color.BLACK);
//ledThread.delay(600);
//delay(1);
}
}
@Override
public void run() {
long ticksPS = 1000 / 30;
long startTime;
long sleepTime;
while(isRunning){
Canvas canvas = null;
startTime = System.currentTimeMillis();
try {
canvas = ledView.getHolder().lockCanvas();
synchronized (ledView.getHolder()){
testTransition(canvas);
}
}finally {
if(canvas != null){
ledView.getHolder().unlockCanvasAndPost(canvas);
}
}
}
}
The variable test[]
is a matrix of 40 elements ( 0 or 1)
private static int test[] = {1,1,1,1,1,1,1,1, 1,0,0,1,0,0,0,1, 1,0,0,1,0,0,0,1, 1,0,0,1,0,0,0,1, 0,1,1,0,1,1,1,0};
My goal is to read this arrangement and simulate that 'on or off' of the pattern of the letter B. But when I execute the code, the activity stays a few seconds with the blank screen and after that the circles appear painted on the bitmap but does not alternate the sequence, although the thread seems to be running. Only the last 8 elements of the test array are drawn
With a SurfaceView
and lockCanvas()
, the screen is not able to update until after you call unlockCanvasAndPost()
. (I think you were expecting the screen to update midway through testTransition()
.)
The solution is to implement a state machine, that dirties the SurfaceView based on a timer (for example), and advances the LED display one row on each iteration.