Reputation: 11
I tried this code and it just doesn't start the animation. the image i putted on the bitmap doesn't move as it should, it's just stay in it's place. i didn't get any errors and i didn't change the XML file.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.view.View;
public class game extends View{
int x = 0;//locations
int y = 0;
public game(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap ball = BitmapFactory.decodeResource(getResources(), R.drawable.t);
super.onDraw(canvas);
Rect rectangle = new Rect();
rectangle.set(0, 0, canvas.getWidth(), canvas.getHeight());
Paint red = new Paint();
red.setColor(Color.RED);
red.setStyle(Paint.Style.FILL);
canvas.drawRect(rectangle, red);
if(x < canvas.getHeight())
x =+ 10;
else
x = 0;
if(y < canvas.getWidth())
y =+ 10;
else
y = 0;
Paint a = new Paint();
canvas.drawBitmap(ball, x, y, a);
invalidate();//repeat the code
}
}
Upvotes: 1
Views: 192
Reputation: 341
call super.onDraw(canvas) at the and of your function, and don't use invalidate() from OnDraw:
protected void onDraw(Canvas canvas) {
Bitmap ball = BitmapFactory.decodeResource(getResources(), R.drawable.t);
Rect rectangle = new Rect();
rectangle.set(0, 0, canvas.getWidth(), canvas.getHeight());
Paint red = new Paint();
red.setColor(Color.RED);
red.setStyle(Paint.Style.FILL);
canvas.drawRect(rectangle, red);
if(x < canvas.getHeight())
x =+ 10;
else
x = 0;
if(y < canvas.getWidth())
y =+ 10;
else
y = 0;
Paint a = new Paint();
canvas.drawBitmap(ball, x, y, a);
super.onDraw(canvas);
}
you can use this method to invalidate your view every X ms:
private void startTimerThread() {
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
try {
int ms = 500 //example of 0.5 sec
Thread.sleep(ms);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
invalidate();
}
});
}
};
new Thread(runnable).start();
}
and call startTimerThread() at your constructor:
public game(Context context) {
super(context);
startTimerThread();
}
Upvotes: 0
Reputation: 1500
Try this -
Paint a= new Paint();
a.setAntiAlias(true);
a.setFilterBitmap(true);
a.setDither(true);
canvas.drawBitmap(ball, x, y, a);
Upvotes: 3