I'm trying to develop a game using a transparent canvas and a surfaceView, I use the canvas to paint and it works fine.
Now I want to add objects that will move on the screen, for example bouncing balls.
I want to use a new thread for the balls, (because otherwise if it's the same thread of the surfaceView it doesn't move smoothly ).
So I'm having trouble of doing this.
Can you please advise me how and when should I send the same canvas to a new ball object and then return it back to the surfaceview.
I'm not sure what the best way to handle this is,
I tried using a ball as a view in the xml layout, and it worked perfect on another thread but it doesn't make sense to create 1000 views when I can just draw them on a canvas.
Any insight will be helpful!
This is my code:
public class SurfaceMyPaint extends SurfaceView implements Runnable
{
Thread t;
SurfaceHolder holder;
Bitmap brush;
boolean isItOk = false;
public SurfaceMyPaint(Context context)
{
super(context);
holder = getHolder();
initial();
}
public void initial()
{
brush= BitmapFactory.decodeResource(getResources(), R.drawable.brush2);
}
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction()== MotionEvent.ACTION_DOWN)
{
x= event.getX();
y= event.getY();
}
if(event.getAction()== MotionEvent.ACTION_MOVE)
{
x = event.getX();
y= event.getY();
}
return true;
}
public void run()
{
while (isItOk == true)
{
if (!holder.getSurface().isValid())
continue;
myCanvas_w = getWidth();
myCanvas_h = getHeight();
if (result == null)
result = Bitmap.createBitmap(myCanvas_w, myCanvas_h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(result);
canvas = holder.lockCanvas(null);
c.drawBitmap(brush, x - (brush.getWidth() / 2), y - (brush.getWidth() / 2), null);
canvas.drawBitmap(result, 0, 0, null);
// How can I add this here: Ball ball = new Ball (canvas)????
holder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
isItOk = false;
while (true){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
t=null;
}
public void resume()
{
isItOk = true;
t = new Thread(this);
t.start();
}
}
Summarizing your rendering code:
Create a screen-sized off-screen bitmap, which you hold in a variable called "result" that isn't declared in the code you show. I assume this is a field, and the allocation only happens once?
Each time, you create a new Canvas for that Bitmap.
You draw on the Bitmap, with drawBitmap().
You copy the Bitmap to the Surface, with drawBitmap().
You want to add a step #5, "draw Ball".
The obvious place to do the ball drawing is in step #3, but I'm going to assume you're not doing it there because that has some relatively static content that you update infrequently but want to blend in every frame.
That being the case, you should just draw the balls onto the Canvas you got back from SurfaceHolder. What you must not do is store a reference to the Surface's Canvas in the Ball object itself, which it appears you want to do (based on new Ball(canvas)). Once you call unlockCanvasAndPost() you must not use that Canvas anymore.
I don't really see an advantage to using multiple threads with your current code. If the "background" Bitmap were also changing you could render that with a different thread, and merge in the current version when you draw, but I suspect that will be more trouble than it's worth -- you will have to deal with the synchronization issues, and I don't think it'll solve your non-smoothness.
Related
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'm trying to create an app that has a fairly complex UI.
I'm trying to understand what is the best practice to render irregular button shapes to the screen.
I'm adding this image as an example. Each one of these wooden boards is a button.
I obviously can't use Android's Button or ImageButton because the shape is not a rectangle.
I assume I need to draw this directly onto a canvas or use onDraw or Draw to make this happen.
Is this the correct way I should use to render these as buttons?
Any good reading material on these is HIGHLY appreciated..
Thank you
You can create a customized View working in following way:
in onDraw() paint 3 bitmaps each representing single button (where 2 other buttons are transparent),
in onTouch() check the touched pixel against those bitmaps to see which bitmap was clicked
Code snippet:
public class DrawingBoard extends View {
Bitmap mBitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.button1);
Bitmap mBitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.button2);
Bitmap mBitmap3 = BitmapFactory.decodeResource(getResources(), R.drawable.button3);
public DrawingBoard (Context context) {
// TODO Auto-generated constructor stub
super (context);
}
#Override
protected void onDraw (Canvas canvas) {
canvas.drawBitmap(mBitmap1, 0, 0, null);
canvas.drawBitmap(mBitmap2, 0, 0, null);
canvas.drawBitmap(mBitmap3, 0, 0, null);
}
#Override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN :
int xx = (int)event.getX();
int yy = (int)event.getY();
if(Color.alpha(mBitmap1.getPixel(xx,yy)) != 0) {
// button1 pressed
}
else if(Color.alpha(mBitmap2.getPixel(xx,yy)) != 0) {
// button2 pressed
}
else if(Color.alpha(mBitmap3.getPixel(xx,yy)) != 0) {
// button3 pressed
}
break;
}
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// bitmaps are assumed to be of the same size
setMeasuredDimension(mBitmap1.getWidth(),mBitmap1.getHeight());
}
}
I didn't test the code, it it may have errors.
A variant - you can create a virtual bitmap storing 'hit codes' for pixels on whole image. You can create it from original picture but replace pixels with ids to detect which area was touched, all other pixels make 'empty' (0x0). So getPixel() will return id of a button.
I've just started playing around with developing an Android app and have run into some troubles.
The intention of this testing app is to draw a square to the screen that moves towards the bottom right of the screen. Simple as that.
MainActivity class (current entry point) looks like so:
Main Activity class (current entry point) looks like so:
public class MainActivity extends Activity {
Canvas canvas;
GameLoopThread gameThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //Super constructor
gameThread=new GameLoopThread(); //Create GameLoop instance
//Create mySurfaceView instance and pass it the new gameloop
MySurfaceView sView=new MySurfaceView(this,gameThread);
//Without this only the bit I cant remove is drawn
sView.setBackgroundColor(Color.TRANSPARENT);
setContentView(sView); //Set the current ContentView to the one we created
//Pass the GameThread the MySurfaceView to repeatedly update
gameThread.setSurfaceView(sView);
gameThread.start(); //Start the thread
}
}
GameLoopThread looks like so:
public class GameLoopThread extends Thread {
protected volatile boolean running;
private MySurfaceView view;
public GameLoopThread(){
}
public void setSurfaceView(MySurfaceView view){
this.view=view;
}
#Override
public void run() {
running=true;
while(running){
Canvas c = null;
c = view.getHolder().lockCanvas(); //Get the canvas
if (c!=null) {
synchronized (view) {
view.draw(c); //Run the doDraw method in our MySurfaceView
}
}
try {
sleep(30, 0); //Throttle
}
catch(InterruptedException e){
e.printStackTrace();
}
if (c != null) {
view.getHolder().unlockCanvasAndPost(c); //Lock and post canvas
}
}
}
public void terminate(){
running=false;
}
}
And finally MySurfaceView looks like so:
public class MySurfaceView extends SurfaceView {
private Bitmap bmp;
private SurfaceHolder holder;
private final GameLoopThread gameLoop;
Paint paint;
float x=0;
float y=0;
public MySurfaceView(Context c, GameLoopThread gThread){
super(c);
holder=getHolder();
gameLoop=gThread;
paint=new Paint();
paint.setColor(Color.CYAN);
paint.setStrokeWidth(10);
holder.addCallback(new CallBack());
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
paint.setColor(paint.getColor() - 1);
canvas.drawRect(x, y, x + 50, y + 50, paint);
x++;
y++;
}
private class CallBack implements SurfaceHolder.Callback{
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoop.terminate();
while (true) {
try {
gameLoop.join();
break;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
}
}
The Issue
This all works, except that one of the initial few draws to the view "sticks". It remains over top of anything drawn at a later date. See below:
I cannot fathom why this is happening. No amount of clearing fixes the problem. If I stop drawing the 'new' square the 'stuck' square remains. You can see I'm varying the color of the 'new' square to test if it changes the 'stuck' one which would indicate it was being redraw. Clearly it isn't.
Drawing nothing for around 4 loops with a 30ms pause in between each draw results in no 'stuck' square. Starting drawing after those initial 4 results in a square that moves across the screen as it should.
Varying the pause time changes how many loops must be waited, but the relationship doesn't appear to be proportional.
Other Info
This is being run on a Samsung Galaxy SIII Mini
SDK verson 4.0.3
A SurfaceView has two parts, a Surface and a View. When you get a Canvas with lockCanvas(), you're getting a Canvas for the Surface part. The Surface is a separate layer, independent of the layer used for all of the View elements.
You've subclassed SurfaceView and provided an onDraw() function, which the View hierarchy uses to render onto the View portion. My guess is that the View hierachy gets an invalidate and decides to draw on the View part of the SurfaceView. Your experiment of skipping the rendering for the first few loop iterations works because you're skipping the render that happens on the invalidate. Because the Surface layer is drawn behind the View layer, you see the onDraw()-rendered square on top of the other stuff you're rendering.
Normally you don't draw on the View; it's just a transparent place-holder, used by the layout code to leave a "hole" in the View layer where the Surface will show through.
Rename onDraw() to doDraw(), and drop the #override. I don't think there's a reason to subclass SurfaceView at all. That should prevent the SurfaceView from drawing on its View.
Of course, if you want to have a mask layer, perhaps to add rounded corners or a "dirt" effect, drawing on the View is an easy way to accomplish it.
See the Graphics Architecture doc for the full story.
I am trying to draw a ball animation over the camera, that is the reason I have to use class View instead of SurfaceView. The point is that is when I run my app, animation is drawing properly sometimes, but if I back to the earlier activity, and return to it, ball draws very slow.
To call the OnDraw method I use the acelerometer:
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mView.invalidate();
}
}
An that`s my OnDraw method:
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
parabolic.getPositions();
int positionY = parabolic.pixY;
int positionX = parabolic.pixX;
ball.setBounds(positionX, positionY,
(int) (positionX + ball.getIntrinsicWidth()),
(int) (positionY + ball.getIntrinsicHeight()));
ball.draw(canvas);
canvas.restore();
}
Where parabolic is an object that I inizialize in the init method:
ParabolicMove parabolic = new ParabolicMove();
And ball is a drawable:
ball = context.getResources().getDrawable(R.drawable.ball);
How could I optimize it do draw well the animation?
You could use a static image to draw the image and the ball in a diferent thread. This may resolve your problem. For more information you can use SurfaceView:
http://developer.android.com/reference/android/view/SurfaceView.html
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.