Is there any way to get objects to foregorund in surfaceView.
for example:
canvas.drawBitmap(...);
canvas.drawText(...);
If I do that text appeared on bitmap. How can I reverse it without redrawing
Sorry for my English.
Canvas just encapsulates bitmap object and bitmap only saves colour of pixel at some position, it doesn't save separate layers. It's like to draw in MSPaint. So you can't change the Z-order of your primitives on canvas. However, why don't you just change the order of commands?
There is no method to bring elements front and back. You are trying to alter the Z-order of the elements here and this is not possible or there is no direct method in Android. All you can do is arrange them in the layout and enable and disable views so that it will give you the same effect.
You can use addView() or setVisibility(View.Visible) to bring bring elements back and front.
Please try to use bellow code.
//SurfaceView class
public class MainGamePanel extends SurfaceView implements
SurfaceHolder.Callback {
MainThread thread;
public MainGamePanel(Context context) {
super(context);
// TODO Auto-generated constructor stub
getHolder().addCallback(this);
setFocusable(true);
thread = new MainThread(getHolder(), this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
Log.e("N", "Changed");
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.e("N", "Created");
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.e("N", "Destroyed");
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (event.getY() > getHeight() - 50) {
thread.setRunning(false);
((Activity) getContext()).finish();
} else {
Log.d("N", "Coords: x=" + event.getX() + ",y=" + event.getY());
}
}
return super.onTouchEvent(event);
}
}
//MainThread class
public class MainThread extends Thread {
// flag to hold game state
private boolean running;
private SurfaceHolder surfaceHolder;
private MainGamePanel gamePanel;
public void setRunning(boolean running) {
this.running = running;
}
public MainThread(SurfaceHolder surfaceHolder, MainGamePanel gamePanel) {
super();
this.surfaceHolder = surfaceHolder;
this.gamePanel = gamePanel;
}
#Override
public void run() {
long tickCount = 0L;
Log.d("N", "Starting game loop");
while (running) {
tickCount++;
// update game state
// render state to the screen
}
Log.d("N", "Game loop executed " + tickCount + " times");
}
}
//Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MainGamePanel(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Related
I'm trying to learn how to use canvas to create simple graphics, but right now it is refusing to draw anything and instead only creates a black background.
Here's the MainActivity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.canvastesting.MainActivity" >
<com.example.canvastesting.DrawingPanel android:id="#+id/DrawingPanel01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:maxHeight="40dip">
</com.example.canvastesting.DrawingPanel>
</RelativeLayout>
DrawingPanel class:
public class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback {
PanelThread canvasthread;
public DrawingPanel(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
canvasthread = new PanelThread(getHolder(), this);
setFocusable(true);
// TODO Auto-generated constructor stub
}
#Override
public void onDraw(Canvas canvas){
//Draw stuff here
canvas.drawColor(Color.TRANSPARENT);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
canvasthread.setRunning(true);
canvasthread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
boolean retry = true;
canvasthread.setRunning(false);
while(retry){
try{
canvasthread.join();
retry = false;
}
catch(InterruptedException e){
}
}
}
}
And my PanelThread class:
public class PanelThread extends Thread{
private SurfaceHolder _surfaceHolder;
private DrawingPanel _panel;
private boolean _run = false;
public PanelThread(SurfaceHolder surfaceHolder, DrawingPanel panel){
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run){
_run = run;
}
#Override
public void run(){
Canvas c;
while(_run){
c = null;
try{
c = _surfaceHolder.lockCanvas(null);
synchronized(_surfaceHolder){
_panel.onDraw(c);
}
}
finally{
if(c!=null){
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
Any help would be much appreciated! I'm completely stumped on this problem.
Add some more code after the line canvas.drawColor(Color.TRANSPARENT); or change the color. Painting a transparent color will show nothing different on the screen. Also, you are missing the super call to onDraw.
Here is the android docs for Canvas where you will find many methods for drawing paths, shapes and bitmaps:
http://developer.android.com/reference/android/graphics/Canvas.html
#Override
public void onDraw(Canvas canvas){
super.onDraw(canvas); ///add missing super
canvas.drawColor(Color.RED);
}
i am trying to run a simple button animation when the game is over
i have the following classes:
GameView
GameThread
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
boolean gameover;GameThread gamethread;
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
gameover=true;
getHolder().addCallback(this); // adding the callback (this) to the surface holder to intercept events
setFocusable(true);// make the GamePanel focusable so it can handle events
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d("TAG", "surface changed");
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
gamethread=new GameThread(getHolder(),this);
gamethread.setrunning(true);
gamethread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry=true;
Log.d("TAG", "Surface destroyed entered");
while(retry){
try {
gamethread.setrunning(false);
gamethread.join();
gamethread=null;
Log.d("tag","thread is destroyed" );
if(gamethread==null){
Log.d("tag","thread is destroyed and null" );
}
retry=false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end while
}//end method
public void update(){
if(gameover){
Button gameover_button = (Button) findViewById(R.id.gameover);
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.gameoveranimation);
gameover_button.startAnimation(animation);
}
}//end update`
public class GameThread extends Thread {
// desired fps
private boolean running;
private SurfaceHolder surfaceholder;
private GameView gameview;
public GameThread(SurfaceHolder surfaceHolder, GameView gameview){
this.gameview=gameview;
this.surfaceholder=surfaceHolder; //we need the surfaceholder since we need to lock surface before drawing
}
public void setrunning(boolean running){
this.running=running;
}
#Override
public void run(){
super.run();
Canvas canvas;
while(running){
canvas=null;
canvas = this.surfaceholder.lockCanvas();
synchronized (surfaceholder) {
if(canvas!=null){
canvas.drawColor(Color.BLACK);
this.gameview.Draw1(canvas);
this.gameview.update();
}//end if
}
}
}finally{//in case of an exception
if(canvas!=null){
surfaceholder.unlockCanvasAndPost(canvas);
}
}//end finally
}//end loop
}//end run
}
<br>
everything works fine except the animation in the update method in the gameview class
the animation runs fine in the oncreate method
i know that my problem is related to thread but i don't know much about them
thx in advance
`
If your issue is that you need to call update on the UI thread, then you can use this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
this.gameview.update();
}
});
Also, it looks like you are looking for your game-over button as a child of your surface view. If that is not correct, you can find the view relative to the parent activity.
Activity activity = (Activity) getContext();
Button gameover_button = (Button) activity.findViewById(R.id.gameover);
I try to display one from list of bitmaps during onDraw.
When i'm passing list to the canvas all are display and stay in their places.
When I pass one random bitmaps it's redrawing canvas all the time.
All works when i'm using public void drawEnemy(Canvas canvas) but not exactly like I want when using public void drawEn(Canvas canvas).
I want to display one random bitmap, then after a few seconds, delete it and display other bitmap. I think the problem is how I implemented onDrow() method. It's redrawing canvas all the time.
Activity:
public class NewGameActivity extends Activity{
NewGame newgame;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Landscape mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// no title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// content Newgame.java
newgame = new NewGame(this);
setContentView(newgame);
}
Thread:
public class MainThread extends Thread{
private SurfaceHolder surfaceHolder;
private NewGame screen;
public MainThread(SurfaceHolder surfaceHolder, NewGame ekran) {
super();
this.surfaceHolder = surfaceHolder;
this.screen= screen;
}
private boolean running;
public void setRunning(boolean running) {
this.running = running;
}
#Override
public void run() {
Canvas canvas;
while (running) {
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
this.screen.onDraw(canvas);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
SurfaceView:
public class NewGame extends SurfaceView implements SurfaceHolder.Callback{
private MainThread thread;
private EnemyManager manager;
public NewGame(Context context) {
super(context);
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
manager = new EnemyManager();
// TODO Auto-generated constructor stub
//adding enemy
Enemy e1 = new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.card), 1);
Enemy e2 = new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.horse), 2);
EnemyLocation l1 = new EnemyLocation(60, 180);
EnemyLocation l2 = new EnemyLocation(60, 50);
manager.AddEnemy(e1, l1);
manager.AddEnemy(e2, l2);
setFocusable(true);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.saloon), 0, 0, null);
manager.drawEn(canvas);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setRunning(false);
thread.stop();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
manager.handleActionDown((int)event.getX(), (int)event.getY());
}
return true;
}
}
EnemyManager:
public class EnemyManager {
private ArrayList<Enemy> enemyList;
private ArrayList<Enemy> suspects;
private Enemy cow;
private String message;
private int suspectID;
private Random rnd;
public String getMessage() {
return message;
}
public EnemyManager(){
enemyList = new ArrayList<Enemy>();
suspects = new ArrayList<Enemy>();
}
public void AddEnemy(Enemy enemy, EnemyLocation loc){
// set x,y enemy localization
enemy.setX(loc.getX());
enemy.setY(loc.getY());
enemyList.add(enemy);
}
public void clearEnemy() {
enemyList.clear();
}
// message if enemy touched
public void handleActionDown(int x, int y) {
for (Enemy enemy: enemyList) {
if (enemy.wasTouched(x, y)) {
message = enemy.getId();
return;
}
}
}
public void PrepareEnemy(){
suspectID = enemyList.get(rnd.nextInt(enemyList.size()+1)).getId();
suspects = new ArrayList<Enemy>();
suspects.add(getSuspectByID(suspectID));
}
private Enemy SingleEnemy(){
Double i = 1 + Math.random() * ((enemyList.size()-1)+1);
cow = getSuspectByID(i.intValue());
return cow;
}
private Enemy getSuspectByID(int suspectID) {
for (Enemy s: enemyList) {
if (s.getId() == suspectID) {
return s;
}
}
return null;
}
public void drawEn(Canvas canvas){
try {
Enemy k = SingleEnemy();
canvas.drawBitmap(cow.picture, cow.x, cow.y, null);
} catch (Exception e) {
// TODO: handle exception
}
}
// draw enemy
public void drawEnemy(Canvas canvas) {
try {
for (Enemy enemy: enemyList) {
canvas.drawBitmap(enemy.picture, enemy.x, enemy.y, null);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
das
As for as understand you are trying to do something like this (if it's not, please correct me):
This is rendering the canvas with all components:
Draw background
Draw enemy
To "refresh" the canvas you simply do something like this:
Draw background
Update
To pause the rendering you could do something like this:
int lastUpdateTime;
int delayTime = 2000; 2 seconds
if(System.currenttimeMillis() > lastUpdateTime + delayTime) {
// Finished waiting
}
You should only define lastUpdateTime when you want to wait and not in every iteration.
NB: Don't call Thread.sleep() in a rendering thread!
This might seem like a silly qustion but how do you change the picture that draws on the screen.I have already been able to program a app were it draws a little icon where you touch the screen.So natually after I completed that I want to make it better by adding a option menu and the ability to change what icon you were being drown but when I ran the code the icon picture stayed the same.When I looked at it I found that when you click on any of the menu item it does do it's job and change the image id but when you go back to the main screen and try to create a new image it revertes back to the old image.I have no idea why it doesn't change because when I look at it everything make sense for it to change icon properly.If any one has any idea on what i am doing wrong or any suggestion on how to do this it would be greatly appreciate
Main
public class main extends Activity {
/** Called when the activity is first created. */
MenuItem item2;
int item3=R.drawable.ic_launcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout sv = new FrameLayout(this);
LinearLayout ll = new LinearLayout(this);
Panel test = new Panel(this);
//ImageButton button = new ImageButton(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(test);
//ll.addView(button);
sv.addView(ll);
setContentView(sv);
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Log.v("test", "item3 before is: "+item3);
item3=R.drawable.box;
Log.v("test", "item3 after is: "+item3);
return super.onOptionsItemSelected(item);
}
}
Panel
public class Panel extends SurfaceView implements SurfaceHolder.Callback {
private Bitmap image;
private ViewThread mThread;
private int x;
private int y;
private ArrayList<Element> mElements = new ArrayList<Element>();
public Panel(Context context) {
super(context );
image = BitmapFactory.decodeResource(getResources(),yantz.imageapp4.R.drawable.test);
getHolder().addCallback(this);
mThread = new ViewThread(this);
}
public void doDraw(Canvas canvas) {
canvas.drawColor(Color.CYAN);
canvas.drawBitmap(image, x, y, null);
synchronized (mElements){
for(Element element : mElements){
element.doDraw(canvas);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.v("test", "you have touched the sreen: ");
synchronized (mElements){
mElements.add(new Element(getResources(),(int) event.getX(),(int) event.getY()));
}
return super.onTouchEvent(event);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!mThread.isAlive()) {
mThread = new ViewThread(this);
mThread.setRunning(true);
mThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mThread.isAlive()) {
mThread.setRunning(false);
}
}
}
Elements
public class Element extends main{
private int mX;
private int mY;
int location ;
private Bitmap mBitmap;
public Element(Resources res, int x, int y) {
Log.v("element", "item3 before location is: "+item3);
location =item3;
mBitmap = BitmapFactory.decodeResource(res, location);
mX = x - mBitmap.getWidth() / 2;
mY = y - mBitmap.getHeight() / 2;
Log.v("element", "item3 before location is: "+item3);
}
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, mX, mY, null);
}
public void setlocation(int location2){
location=location2;
}
}
ViewThread
public class ViewThread extends Thread {
private Panel mPanel;
private SurfaceHolder mHolder;
private boolean mRun = false;
public ViewThread(Panel panel) {
mPanel = panel;
mHolder = mPanel.getHolder();
}
public void setRunning(boolean run) {
mRun = run;
}
#Override
public void run() {
Canvas canvas = null;
while (mRun) {
canvas = mHolder.lockCanvas();
if (canvas != null) {
mPanel.doDraw(canvas);
mHolder.unlockCanvasAndPost(canvas);
}
}
}
}
you can use
#Override
protected void onResume() {
super.onResume();
id="what ever you want";
//and set it to imagevIew;
}
if i have understood the uestion correctly,this happens because your activity pauses when it is not focused and resumes with default values.
I have created a class like this:
public class nir extends Activity implements OnClickListener{
/** Called when the activity is first created. */
ImageButton btnNew, btnPlay, btnSignUp;
TextView txtTitle;
Typeface font;
//sprite
SurfaceView pet;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
font = Typeface.createFromAsset(getAssets(), "fonts/aaaiight.ttf");
btnNew = (ImageButton)findViewById(R.id.btnNew);
btnNew.setOnClickListener(this);
btnPlay = (ImageButton)findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
txtTitle = (TextView)findViewById(R.id.lblTama);
txtTitle.setTypeface(font);
//sprite
//setContentView(new MainGamePanel(this));
}
}
Now I want to make that SurfaceView show any sprite. I've tried
<view class="Tamagotchi.nir.MainGamePanel...">
in my XML, but it gives me a "Force Close" dialog.
I also have this class:
public class MainGamePanel extends SurfaceView implements
SurfaceHolder.Callback {
private static final String TAG = MainGamePanel.class.getSimpleName();
private MainThread thread;
private Sprite elaine;
// the fps to be displayed
private String avgFps;
public void setAvgFps(String avgFps) {
this.avgFps = avgFps;
}
public MainGamePanel(Context context) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
// create Elaine and load bitmap
elaine = new Sprite(
BitmapFactory.decodeResource(getResources(),
R.drawable.walk_elaine),
10, 50, // initial position
30, 47, // width and height of sprite
5, 5); // FPS and number of frames in the animation
// create the game loop thread
thread = new MainThread(getHolder(), this);
// make the GamePanel focusable so it can handle events
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// at this point the surface is created and
// we can safely start the game loop
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "Surface is being destroyed");
// tell the thread to shut down and wait for it to finish
// this is a clean shutdown
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}
Log.d(TAG, "Thread was shut down cleanly");
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// handle touch
}
return true;
}
public void render(Canvas canvas) {
canvas.drawColor(Color.BLACK);
elaine.draw(canvas);
// display fps
displayFps(canvas, avgFps);
}
/**
* This is the game update method. It iterates through all the objects
* and calls their update method if they have one or calls specific
* engine's update method.
*/
public void update() {
elaine.update(System.currentTimeMillis());
}
private void displayFps(Canvas canvas, String fps) {
if (canvas != null && fps != null) {
Paint paint = new Paint();
paint.setARGB(255, 255, 255, 255);
canvas.drawText(fps, this.getWidth() - 50, 20, paint);
}
}
}
What is the reason for the crash?
Take out view class =
in front of Your package name all you need is the package name.YourSurfaceViewClass
This is how your code should look
<Tamagotchi.nir.MainGamePanel.YourSurfaceViewClassName
android:id="#+id/myView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>