Reputation: 2626
In my application, i want to get something like this.
And here is the code
public class Tunnel extends View {
Paint paint = new Paint();
Toast toast;
public Tunnel(Context context) {
super(context);
setBackgroundColor(Color.BLACK);
paint.setColor(Color.WHITE);
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (toast != null) {
toast.cancel();
}
int x = (int) event.getX();
int y = (int) event.getY();
if (y > myFunction(x) + 100 || y < myFunction(x)) {
toast = Toast.makeText(getContext(), "Out of bounds", Toast.LENGTH_SHORT);
} else {
toast = Toast.makeText(getContext(), "Perfect", Toast.LENGTH_SHORT);
}
toast.show();
return false;
}
});
}
@Override
public void onDraw(Canvas canvas) {
for (int x = 0; x < canvas.getWidth(); x++) {
//upper bound
canvas.drawPoint(x, (float) myFunction(x), paint);
//lower bound
canvas.drawPoint(x, (float) myFunction(x) + 100, paint);
canvas.drawLine(x, (float) myFunction(x), x, (float) myFunction(x) + 100, paint);
}
}
private double myFunction(double x) {
return 50 * Math.sin(x / 50) + 400;
}
}
But instead of that, I'm getting a white screen. The onDraw method works fine, i've tested it with red color, but why doesn't the setBackgroundColor work? what am i doing wrong?
Upvotes: 0
Views: 93
Reputation: 2626
Okay, i found out the problem. I need to move the line
setBackgroundColor(Color.BLACK);
into the onDraw
method, so my it will look like this
@Override
public void onDraw(Canvas canvas) {
for (int x = 0; x < canvas.getWidth(); x++) {
//upper bound
canvas.drawPoint(x, (float) myFunction(x), paint);
//lower bound
canvas.drawPoint(x, (float) myFunction(x) + 100, paint);
canvas.drawLine(x, (float) myFunction(x), x, (float) myFunction(x) + 100, paint);
}
setBackgroundColor(Color.BLACK);
}
Upvotes: 1