I want an action to be performed when the view is touched. However, the touches do not respond. The app doesn't crash, it just seems to ignore it.
public class CustomDrawableView extends View implements OnTouchListener
{
static final int width = 100;
static final int height = 50;
public CustomDrawableView(Context context)
{
super(context);
setFocusable(true);
setOnTouchListener(mCustomDrawableView);
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN )
{
x = 400;
return true;
}
else {
x = 300;
return false;
}
}
protected void onDraw(Canvas canvas)
{
int mCanvasHeight = canvas.getHeight();
int mCanvasWidth = canvas.getWidth();
canvas.save();
canvas.rotate(R,x,y);
if (y >= mCanvasHeight-100) {
y = 0;
}
RectF oval = new RectF(x, y, x + width, y
+ height); // set bounds of rectangle
Paint p = new Paint(); // set some paint options
p.setColor(Color.BLUE);
canvas.drawOval(oval, p);
canvas.restore();
invalidate();
}
}
I have tried a bunch of different code to fix it. None of it does anything except if I change setOnTouchListener(mCustomDrawable) to mCustomDrawableView.setOnTouchListener(this) the app crashes. There is a bunch more code in the activity that I did not put up.
I'm guessing you believe that the onTouch() isn't firing because you're not seeing your graphics change in response to changes in x or whatever. If that's the case, it looks like you're missing a call to invalidate() in your touch handler to cause the View to redraw itself again (via a call to onDraw()).
Also, you have an invalidate() actually inside onDraw() itself which really shouldn't be there. It would certainly cause your View to redraw itself over and over - I suppose - so actually, I guess you should be seeing updates because that's there. But that isn't the way you should make a View animate; you should instead use a Thread or Handler to schedule a regular, periodic invalidate() - or some other means to regularly schedule an update.
Also there should be no need to implement 'OnTouchListener' when you can just override onTouch() as you have done. There are a couple of ways you can detect touch events for a View: (1) Override onTouch() as you have done, to get touch events on that View. (2) Register a listener using setOnTouchListener(). This latter option enables you to have a listener that listens to touch events from one View or multiple Views, and it also 'sees' touch events before a registered View's own onTouch() sees them.
Another thing I see is that you're setting x to 400 when you get an ACTION_DOWN event but then you're setting it to 300 for any other kind of event such as an ACTION_MOVE. Considering it's actually quite difficult to keep your finger still enough to never cause a string of ACTION_MOVE events immediately after an ACTION_DOWN, perhaps you're just never seeing the graphics when x is at 400 or something.
You really need to post a complete example (for instance your code as you've posted has setOnTouchListener(mCustomDrawableView) where mCustomDrawableView has not been defined anywhere) together with specific errors from Logcat. Also, you should use the debugger to see if your onTouch ever executes (stick a breakpoint in it).
Also, you should accept some answers.
Related
I'm doing a school project. In this project I have to do a program that have one or more ball bouncing in the screen. I did some research on google to help me in this, and I found this code :
public class BouncingBallInside extends View {
private List<Ball> balls = new ArrayList<>();
public BouncingBallInside(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BouncingBallInside(Context context) {
super(context);
init();
}
private void init(){
//Add a new ball to the view
balls.add(new Ball(50,50,100, Color.RED));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Draw the balls
for(Ball ball : balls){
//Move first
ball.move(canvas);
//Draw them
canvas.drawOval(ball.oval,ball.paint);
}
invalidate(); // See note
}
}
The ball class :
public class Ball{
public int x,y,size;
public int velX = 10;
public int velY=7;
public Paint paint;
public RectF oval;
public Ball(int x, int y, int size, int color){
this.x = x;
this.y = y;
this.size = size;
this.paint = new Paint();
this.paint.setColor(color);
}
public void move(Canvas canvas) {
this.x += velX;
this.y += velY;
this.oval = new RectF(x-size/2,y-size/2,x+size/2,y+size/2);
//Do we need to bounce next time?
Rect bounds = new Rect();
this.oval.roundOut(bounds); ///store our int bounds
//This is what you're looking for ▼
if(!canvas.getClipBounds().contains(bounds)){
if(this.x-size<0 || this.x+size > canvas.getWidth()){
velX=-velX;
}
if(this.y-size<0 || this.y+size > canvas.getHeight()){
velY=-velY;
}
}
}
}
The program works perfecly.
I studied it deeply as good as I could. But after it and after watching the documentation I couldn't understand two thing:
Where and when the method onDraw(Canvas canvas) is called the first time.
Why at the end of onDraw there is invalidate()?
I mean the documentation said :
Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future.
so... if this method is used to call onDraw,why don't call it direcly? what's the difference?
1)The onDraw method will be called by the framework, whenever the view is invalid. A view is invalid when it first comes on screen, so when you set your content view for an activity they layout and all views in it will be measured, laid out, then drawn (via onDraw).
After that the UI thread will call onDraw if needed every 16ms or so (so it draws at 60 FPS).
2)Its marking the view as needing to be redrawn, so the next time the the screen is drawn onDraw will be called. Otherwise it would be skipped, as we could assume it isn't needed.
Why you don't call onDraw directly- efficiency. In a very simple drawing system you would- but drawing is time consuming, you don't want to do it more than you have to. So instead of drawing immediately (which wouldn't work anyway, you wouldn't have the right Canvas to pass to onDraw), you call invalidate and the system will call onDraw if needed at a regular interval.
Note that this isn't particularly good code. In particular, having the onDraw trigger the move which updates the balls location instead of using a timer is icky. Having onDraw call invalidate as a result is also kind of icky. A better solution would be to separate the view, model, and timer into more of an MVC or MVP system.
currently I am trying to make an animation where some fish move around. I have successfully add one fish and made it animate using canvas and Bitmap. But currently I am trying to add a background that I made in Photoshop and whenever I add it in as a bitmap and draw it to the canvas no background shows up and the fish starts to lag across the screen. I was wondering if I needed to make a new View class and draw on a different canvas or if I could use the same one? Thank you for the help!
Here is the code in case you guys are interested:
public class Fish extends View {
Bitmap bitmap;
float x, y;
public Fish(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fish1);
x = 0;
y = 0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap, x, y, null);
if (x < canvas.getWidth())
{
x += 7;
}else{
x = 0;
}
invalidate();
}
}
You can draw as many bitmaps as you like. Each will overlay the prior. Thus, draw your background first, then draw your other images. Be sure that in your main images, you use transparent pixels where you want the background to show through.
In your code, don't call Invalidate() - that's what causes Android to call onDraw() and should only be called from somewhere else when some data has changed and needs to be redrawn.
You can do something like this, where theView is the view containing your animation:
In your activity, put this code in onCreate()
myAnimation();
Then
private void myAnimation()
{
int millis = 50; // milliseconds between displaying frames
theView.postDelayed (new Runnable ()
{
#Override public void run()
{
theView.invalidate();
myAnimation(); // you can add a conditional here to stop the animation
}
}, millis);
}
I want to develop a game that shoots bullets on every touch of the canvas.
It works but when I touch the canvas after shooting, he takes the bullet and restarts the shooting.
I just want the bitmap to create new bullet at every touch. Here is my code:
public class MainActivity extends Activity implements OnTouchListener {
DrawBall d;
int x ;
int y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
d = new DrawBall(this);
d.setOnTouchListener(this);
setContentView(d);
}
public class DrawBall extends View {
Bitmap alien;
public DrawBall(Context context) {
super(context);
alien = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
startDraw(canvas);
}
public void startDraw(Canvas canvas){
Rect ourRect = new Rect();
ourRect.set(0,0, canvas.getWidth(), canvas.getHeight());
Paint blue = new Paint();
blue.setColor(Color.BLACK);
blue.setStyle(Paint.Style.FILL);
canvas.drawRect(ourRect, blue);
if(y < canvas.getHeight()){
y-=5;
}
canvas.drawBitmap(alien, x, y,new Paint());
invalidate();
}
}
public boolean onTouch(View v, MotionEvent event) {
x = (int) event.getX();
y = (int) event.getY();
return false;
}
}
I only superficially read the code. It seems that you are only keeping track of one bullet using the x y coordinates.The coordinates are resetting at every touch event, and thus you lose the previous bullet.
Use a dynamic array, or a linked list to keep track of all the bullets on the screen.
When there's a new touch, add the x,y to the array.
When drawing the bullet, iterate through your array to draw and update every bullet.
If the y-coordinate of any bullet goes out of the screen, delete the bullet from the array.
Each draw starts with a blank canvas. So to draw multiple bitmaps you need to keep track of where to draw each bullet and call drawBitmap multiple times.
Also, calling invalidate in onDraw is a bad idea- it will immediately invalidate, leading you to have performance issues. I'd suggest invalidating on a timer instead. Drawing too frequently will lead to performance issues.
I have drawn a bitmap image over a canvas.
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.sq);
canvas.drawColor(color.black);
Rect dstRectForRender = new Rect(0,0,320,450);
canvas.drawBitmap(image, null,dstRectForRender,null);
The image gets displayed based on my screnn on a cnavs.
On my touch input, I need to pass the x and y co-ordinate position of the image and fill that pixel with a color to show that the image is painted on a drag event.
How can I pass the x and y coo-ordinate parameters? Which functions should I use to plot the pixels on the image?
I appreciate your help and sweet time.
I'm not sure if this is the best way to do this, but it would be much easier to do this if you defined your own subclass of ImageView and name it something like DrawableImageView. You'd have to make sure you implement all the basic constructors from ImageView, then override the onTouchEvent method. From that event you can get the touch coordinates and store them in an ArrayList<Point> and use that ArrayList by overriding the onDraw method and "painting" the image.
public class DrawableImageView extends ImageView {
ArrayList<Point> list = new ArrayList<Point>();
//constructors..
#Override
public boolean onTouchEvent (MotionEvent event) {
float x = event.getX();
float y = event.getY();
list.add(new Point(x,y));
invalidate();
}
This is just a very brief overview of how to start your class, and may not be the most accurate way of doing things (depending on your specific code). Now, instead of using <ImageView> tags in your xml (or, loading an ImageView programatically), you refer to your subclass like so:
<your.package.name.DrawableImageView
/>
Edit
In response to your comment, there is no predetermined way to draw over an image. You must implement this yourself, which is why I recommended storing Points in an ArrayList. I'm not really sure what you're trying to achieve here, but to draw (for example) black dots over an image you have to override onDraw:
public void onDraw(Canvas c) {
super.onDraw(c);
for(Point p : list) {
//Draw black point at x and y.. I'm posting from my cell so I can't go into much detail
}
}
Also, to force a View to redraw itself you need to use the invalidate() method in your onTouchEvent() (which I've added above).
I've fooling around with 2D graphics in the Android SDK and I'm having trouble with what should be a simple example.
I'm assuming that I'm just misunderstanding something fundamental/basic.
public class DrawView extends View {
Paint paint = new Paint();
Canvas canvas = new Canvas();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
#Override
public void onDraw(Canvas canvas) {
this.canvas = canvas;
this.canvas.drawLine(0,0, 500, 500, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("DrawView", "onTouchEvent: " + event.getX() + "," + event.getY() );
canvas.drawLine(0,500, 500, 0, paint);
return true;
}
}
The code above draws a single line from 0,0 to 500,500 when the app start. That parts works just fine.
The issue is that the second line isn't drawn on the touch event. The onTouchEvent is definitely being called because I see the coordinates debug message in the log.
Can someone point out what silly thing I'm doing wrong?
You're supposed to call invalidate() at the end of onTouchEvent() to tell the system to update the screen. Calling invalidate() will call onDraw().
Also, what is fundamentally wrong is that you create a canvas in this class you have. That does absolutely nothing for you. The canvas to draw in is the one that you get from the onDraw() method. The call to canvas.drawLine() in onTouchevent isn't doing anything for you and shouldn't be there. That is an empty canvas and isn't the one that will get "posted."
In onTouchEvent() you should only gather the touch event data, and also do some processing on it if you need to. You shouldn't make any calls to drawing methods there. However, as I said, if you want to trigger a draw from onTouchEvent(), you call invalidate(). If you want to draw lines based on where you are touching, you will need to create class variables that are X and Y coordinates. You update these X and Y variables in onTouchEvent(), and then you use them in onDraw() to draw whatever you need based on these X and y variables.
Call postInvalidate() function. This function inform that view should be redrawed (event loop call onDraw() function).
You can declare a bool variable in your class, so that you can pass it to your ondraw() method that the user has touched and also pass X and Y with other float variables to ondraw() methode !
But you have to vall invalidate in onTouchEvet() so that the system will redraw the canvas using your new touch orders!