I have the following code that blows the app. Methods like drawLine work fine if they are directly inside "onDraw" but not if placed outside in a separate method as shown below. Does anyone have any idea what's wrong? The version with the method compiles ok but the app crashes when started.
Many thanks Roberto
public class Painter extends View {
private static Canvas canvas;
private static Paint paintG = null;
public static int screenW; // screen width
public static int screenH; // screen height
private String tag = "Painter";
public Painter(Context context) {
super(context);
readDrawingData();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
screenW = canvas.getWidth(); // screen width
screenH = canvas.getHeight(); // screen height
Rect allScreen = new Rect(0, 0, screenW, screenH);
// works OK
paintG = new Paint();
paintG.setAntiAlias(true);
paintG.setStrokeWidth(2);
paintG.setStyle(Paint.Style.FILL);
paintG.setColor(0xFFf7f9d2);
canvas.drawRect(allScreen, paintG);
// paint circle/oval - works OK
double R = ((screenW > screenH) ? screenH : screenW) / 2 - 100;
double Z = R + 20;
double X = screenW /2;
double Y = screenH /2;
RectF oval1 = new RectF(Math.round(X-R), Math.round(Y-R),
Math.round(X+R), Math.round(Y+R));
paintG.setStyle(Paint.Style.STROKE);
paintG.setColor(0xffff0000);
canvas.drawOval(oval1, paintG);
// this code works OK here
paintG.setColor(0xffff0000);
if (i > 0) {
for (int j=0; j<i; j++) {
canvas.drawLine(x1[j], y1[j], x2[j], y2[j], paintG);
}
}
// calling this will crash app
paintDrawing();
}
// ************************************************************
void paintDrawing() {
// PROBLEM: same code as above - causes app to crash...
// when outside onDraw
paintG.setColor(0xffff0000);
if (i > 0) {
for (int j=0; j<i; j++) {
canvas.drawLine(x1[j], y1[j], x2[j], y2[j], paintG);
}
}
// ************************************************************
}