I want to control drawing on Surface View from MainActivity
. (user) Github link of the project is given at the end of the post.
MainActivity
callsdraw(Drawing)
method on SurfaceView instance.
I have following code, the surface view only draws when I enabled breakpoint debugging.
I already visited these links, no solution found:
Drawing using the Surfaceview creates blank screen
Android drawing on surfaceview and canvas
Tutorials I folowed:
Drawing Triangles, Rhombuses and Other Custom Shapes on an Android Canvas
Android Coding - Drawing on SurfaceView
I thought it was a matter of view creation being in the process so I added checks for creation:
public void draw(Drawing drawing) {
this.drawing = drawing;
if (surfaceHolder.isCreating()) {
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
thread = new Thread(LushSurfaceView.this);
thread.start();
}
});
} else {
thread = new Thread(this);
thread.start();
}
}
Here is thread:
@Override
public void run() {
if (drawing != null) {
switch (drawing) {
case RECT:
drawRectShape();
break;
}
}
}
Also I added delays deliberately to wait for the surface view initialization.
private void drawRectShape() {
if (surfaceHolder.getSurface().isValid()) {
Canvas canvas = surfaceHolder.lockCanvas();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (canvas != null && !surfaceHolder.isCreating()) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(30);
Random random = new Random();
int w = canvas.getWidth();
int h = canvas.getHeight();
int left = Math.round(w/2);
int top = Math.round(h/2);
int right = 200;
int bottom =200;
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
canvas.drawRect(new Rect(left, top, right, bottom), paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
- Code works when: I enable breakpoint debugging.
- Simple debugging does not show anything drawn.
- I recreated this scenario several times.
I am using Nexus 6 (OS 7.1.1) as testing device. (Not Emulator).
Project source at github.