How to create Rain Effect in surfaceView? - java

I'm trying to create a rain effect in android. I have already created the sprite class, what I don't know is how to do that appear X amount of drops per second or the time of life. Can somebody help me?
Thanks.
This is my code
Sprite class:
public class Sprite_Rain {
private Bitmap rain_drop;
private Game game;
private int speed = 50;
int x, y = -100;
boolean position = true;
Paint paint;
public Sprite_Rain(Game game, Bitmap rain_drop){
this.game = game;
this.rain_drop= rain_drop;
paint = new Paint();
}
public void onDraw(Canvas canvas) {
if (position == true) {
Random random = new Random();
x = random.nextInt(canvas.getWidth());
position = false;
}
canvas.drawBitmap(rain_drop, x, y, null);
}
}
Game class:
public class Game extends SurfaceView {
private Bitmap rain_drop;
private Sprite_Rain sprite_rain;
Paint paint;
private List<Sprite_Rain> sprites = new ArrayList<Sprite_Rain>();
public Game(Context context, AttributeSet attrs) {
super(context, attrs);
rain_drop = BitmapFactory.decodeResource(getResources(), R.drawable.rain_drop);
sprite_rain = new Sprite_Rain(this, rain_drop);
paint = new Paint();
}
private Sprite_Rain createSprite(int resource) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resource);
return new Sprite_Rain(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
paint.setColor(Color.BLACK);
int i = 0;
for (Sprite_Rain sprite : sprites) {
sprite.onDraw(canvas);
i++;
}
invalidate();
}
}

Related

How to draw multiple points on imageview in android java

I'm setting up an eye detection android project and I want to draw probabilities using Canvas, I'm using Firebase ML kit for custom models
I have successfully drawn only one point.
I would like to draw points ( probabilities from tflite model that I have ).
I tried using those functions :
private void useInferenceResult(float[] probabilities) throws IOException {
// [START mlkit_use_inference_result]
String[] result=new String[80];
float x=0;
float y=0;
ArrayList<Point> listpoint= new ArrayList<Point>();
for (int i = 0; i < probabilities.length; i++) {
Log.i("MLKit", String.format("%1.4f", probabilities[i]));
x=probabilities[i];
y=probabilities[i+1];
Point p=new Point(x,y);
i=i+1;
p.setX(x);
p.setY(y);
Log.i("Information1 ","valeur 1 "+p.getX());
listpoint.add(p);
Log.i("Information2 ","valeur 2 "+p.getX());
}
for(int j=0;j<listpoint.size();j++){
Log.e("Information","work");
Log.e("Resultat","point_"+j+"("+listpoint.get(j).getX()+", "+listpoint.get(j).getY()+")");
float xx=listpoint.get(j).getX()*100;
float yy=listpoint.get(j).getY()*100;
drawpoint(image2,0.20958422f * 100,0.6274962f * 100,1);
drawpoint(image2, 0.20460524f * 100,0.6708223f * 100,1);
}
}
//drawpoint function
private void drawpoint(ImageView imageView,float x,float y, int raduis){
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.imgg,myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x,y, raduis, paint);
imageView = (ImageView)findViewById(R.id.imageView);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
but I didn't get any result just one point drawn.
How can I draw multiples points on imageView?
I solved my problem by changing some lines of code, I declare those variables on the top and I create objects after setContentView:
BitmapFactory.Options myOptions;
Canvas canvas;
Bitmap mutableBitmap;
Bitmap workingBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_open= findViewById(R.id.btn_open);
image2= findViewById(R.id.imageView);
myOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.image000880,myOptions);
paint= new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
workingBitmap = Bitmap.createBitmap(bitmap);
mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
canvas = new Canvas(mutableBitmap);
private void drawpoint(ImageView imageView,float x,float y, int raduis){
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
// ArrayList<Point> list= new ArrayList<>();
canvas.drawCircle(x,y, raduis, paint);
imageView = (ImageView)findViewById(R.id.imageView);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
Hope this solution will help others who have the same situation
Simple ImageView Descendent class.
public class CiclesImageView extends AppCompatImageView {
private ArrayList<PointF> theDots = new ArrayList<>();
private Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
public CirclesImageView(Context context) {
super(context);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
drawDot(new PointF(event.getX(),event.getY()));
return performClick();
}
});
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
for (PointF pt:theDots)canvas.drawCircle(pt.x,pt.y,5,paint);
}
public void drawDot(PointF dotPoint){
theDots.add(dotPoint);
invalidate();
}
}
This imageView is used the same way you use any other imageView, except if you touch it, it will draw a circle on itself. If you want to draw your own circles, the drawDot(pointF) is public.

Temporary Sprite in Android App

I have an android game where there are sprites moving about the screen. When one is hit, it adds or takes away from the score and then disappears.
What I would like it to do is create a blood splatter when it is hit which will also disappear.
I have actually achieved this but the blood splatter doesn't appear where the sprite was hit. It always goes to the bottom right-hand corner. I was wondering if there is anyone out there that can see where my problem is.
I have a TempSprite class just for the blood splatter and this is below:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
All the other code is in the GameView class, specifically in the doDraw and GameView methods:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private final Bitmap bmpBlood;
/* Member (state) fields */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
private BadSprite badSprite;
// For recording the number of hits
private int hitCount;
// For displaying the highest score
private int highScore;
// To track if a game is over
private boolean gameOver;
// To play sound
private SoundPool mySound;
private int zapSoundId;
private int screamSoundId;
// For multiple sprites
private ArrayList<Sprite> spritesArrayList;
private ArrayList<BadSprite> badSpriteArrayList;
// For the temp blood image
private List<TempSprite> temps = new ArrayList<TempSprite>();
//int backButtonCount = 0;
private void createSprites() {
// Initialise sprite object
spritesArrayList = new ArrayList<>();
badSpriteArrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
spritesArrayList.add(new Sprite(this));
badSpriteArrayList.add(new BadSprite(this));
}
}
public GameView(Context context) {
super(context);
// Focus must be on GameView so that events can be handled.
this.setFocusable(true);
// For intercepting events on the surface.
this.getHolder().addCallback(this);
// Background image added
mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.castle);
// Populate multiple sprites
//createSprites();
//Vibrator vibe = (Vibrator) sprite.getSystemService(Context.VIBRATOR_SERVICE);
//vibe.vibrate(500);
// For the temp blood splatter
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
//Sound effects for the sprite touch
mySound = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
screamSoundId = mySound.load(context, R.raw.scream, 1);
zapSoundId = mySound.load(context, R.raw.zap, 1);
}
/* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
// We can now safely setup the game start the game loop.
ResetGame();//Set up a new game up - could be called by a 'play again option'
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
gameLoopThread = new GameLoopThread(this.getHolder(), this);
gameLoopThread.running = true;
gameLoopThread.start();
}
// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen
//To initialise/reset game
private void ResetGame(){
/* Set paint details */
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
sprite = new Sprite(this);
hitCount = 0;
// Set timer
startTime = 10; // Start at 10s to count down
// Create new object - convert startTime to milliseconds
countDownTimer = new MyCountDownTimer(startTime*1000, interval);
countDownTimer.start(); // Start the time running
timerRunning = true;
gameOver = false;
}
// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer (long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
//displayTime = "Time is up!";
timerRunning = false;
countDownTimer.cancel();
gameOver = true;
}
public void onTick (long millisUntilFinished) {
displayTime = " " + millisUntilFinished / 1000;
}
}
//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){
}
/**
* To draw the game to the screen
* This is called from Thread, so synchronisation can be done
*/
#SuppressWarnings("ResourceAsColor")
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBackgroundImage, 0, 0, null);
if (!gameOver) {
sprite.draw(canvas);
//paint.setColor(R.color.red);
canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
canvas.drawText("Number of hits: " + hitCount, 35, 85, paint);
// Draw the blood splatter
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
// Draw all the objects on the canvas
for (int i = 0; i < spritesArrayList.size(); i++) {
Sprite sprite = spritesArrayList.get(i);
sprite.draw(canvas);
}
for (int i = 0; i < badSpriteArrayList.size(); i++) {
BadSprite badSprite = badSpriteArrayList.get(i);
badSprite.draw(canvas);
}
} else {
canvas.drawText("Game Over!", 35, 50, paint);
canvas.drawText("Your score was: " + hitCount, 35, 80, paint);
canvas.drawText("To go back home,", 280, 50, paint);
canvas.drawText("press the 'back' key", 280, 70, paint);
}
}
//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
for (int i = spritesArrayList.size()-1; i>=0; i--) {
Sprite sprite = spritesArrayList.get(i);
if (sprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(zapSoundId, 1.0f, 1.0f, 0,0, 1.5f);
spritesArrayList.remove(sprite);
//temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount--;
return super.onTouchEvent(event);
}
for (int i1 = badSpriteArrayList.size()-1; i1>=0; i1--) {
BadSprite badSprite = badSpriteArrayList.get(i1);
if (badSprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(screamSoundId, 1.0f, 1.0f, 0, 0, 1.5f);
badSpriteArrayList.remove(badSprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount++;
return super.onTouchEvent(event);
}
}
}
//else {
return true;
// }
}
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoopThread.running = false;
// Shut down the game loop thread cleanly.
boolean retry = true;
while(retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public int getHitCount() {
return hitCount;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
As always, any help greatly appreciated.
Thanks
This was solved with the following code:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
/*this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());*/
this.x = x;
this.y = y;
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
You can see where the commented out sections are and below are what they were replaced with. I was trying to make things a little too complicated.

Issues with my Android custom sprite Class

I am currently designing a basic sprite class for java for android because for I don't wish to use a 2d engine and Google doesn't provide any sprite APIs for some reason...
Anyways, my question is in regards to my Classes I have designed. I have a Sprite Class that takes a bitmap and turns it into a "sprite". This sprite can then be passed to a custom view I have created when the user creates a new "SpriteContainer"
My code for the DynamicSpriteContainer is as follows:
package com.me.spriteGraphics;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class DynamicSpriteContainer extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
public int x, y;
private Bitmap b;
public Sprite sprite;
private Canvas c = new Canvas();
private boolean bool = false;
public DynamicSpriteContainer(Context context, Sprite spriteImage) {
//public ImageView(Context context) {
super(context);
//get sprite
b = spriteImage.getBitmap();
//set holder
holder = getHolder();
holder.addCallback(this);
//set position
x = y = 0;
update();
}
public void surfaceCreated(SurfaceHolder holder) {
c = holder.lockCanvas();
c.drawARGB(255, 150, 150, 10);
//set up bitmap image
c.drawBitmap(b, x, y, null);
holder.unlockCanvasAndPost(c);
update();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
private void update() {
//this code will alter the character in the way the developer specifies (per frame)
Thread repeat = new Thread( new Runnable() {
public void run() {
try {
//move sprite in constant motion
while (bool) {
//redraw
c = holder.lockCanvas();
c.drawARGB(255, 150, 150, 10);
//set up bitmap image
c.drawBitmap(b, x, y, null);
holder.unlockCanvasAndPost(c);
}
} catch (Error e) {
e.printStackTrace();
bool = false;
}
}
});
repeat.start();
}
public void setX(int x) {
//notice how this same code above has the holder, the holder is recognized above, not here.
c = holder.lockCanvas();
c.drawARGB(255, 150, 150, 10);
//set up bitmap image
c.drawBitmap(b, x, y, null);
holder.unlockCanvasAndPost(c);
}
//set the info on pause, resume, stop...
//this data is for error stopping, so the app can resume and stop without passing an error to the user!
public void passInfo(boolean isPaused, boolean isResumed, boolean isStopped) {
if (isPaused && sprite.auto) {
bool = false;
}
if (isResumed && sprite.auto) {
bool = true;
}
if (isStopped && sprite.auto) {
bool = false;
}
}
}
Sorry for the long code excerpt.
The main issue is that inside the update() function, the holder is recognized, but inside the setX(), it's not...
How can I have the setX() recognize the holder?
Thank you soo much in advance!!!

Android: How can I multiply a class and create different instances of its variables?

I'm new to Java, so I hope it's not a silly question. I have a class called "Enemy".
I know how to multiply the class, I use the "for" loop. Now, the problem is that the variables x and y (the one's that move the bitmap) have the same values for every instance of the class. And I want them to be different in order to create some "randomness".
The main class:
public class MainActivity extends Activity{
Player ourView;
#SuppressLint("ClickableViewAccessibility") protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ourView = new Player(this);
setContentView(ourView);
}
protected void onPause() {
super.onPause();
ourView.pause();
}
protected void onResume() {
super.onResume();
ourView.resume();
}
}
Here's the "Player" class:
public class Player extends SurfaceView implements Runnable {
Canvas canvas = new Canvas();
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = true;
public Player(Context context) {
super(context);
ourHolder = getHolder();
ourThread = new Thread(this);
ourThread.start();
}
public void pause() {
isRunning = false;
while(true){
try{
ourThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
}
public void run() {
while(isRunning) {
if(!ourHolder.getSurface().isValid())
continue;
canvas = ourHolder.lockCanvas();
canvas.drawRGB(30, 30, 200);
Enemy[] enemy = new Enemy[3];
for(int i = 0; i<enemy.length; i++){
enemy[i] = new Enemy(null);
enemy[i].draw();
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
And here's the "Enemy" class:
public class Enemy extends Player{
public Enemy(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
float x,y = (float) (Math.random()*200);
public void draw(){
Bitmap bitmap = (Bitmap) BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bitmap, x, y, null);
}
}
I've also tried to declare those variables inside the "Enemy" class, but they just don't work. The bitmap stays in (0,0).
NOTE: The "Player" and "Enemy" class are declared inside the "MainActivity" class.
Your Enemy class should not extend the Player class since they don't share any similarities except the canvas and the context.
A possible implementation of your Enemy could look like this:
public class Enemy {
private Bitmap bitmap;
private Canvas canvas;
private Context context;
private float x, y;
public Enemy(Canvas canvas, Context context) {
bitmap = BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_launcher);
x = (float) (Math.random() * 200);
y = (float) (Math.random() * 200);
}
public void draw() {
canvas.drawBitmap(bitmap, x, y, null);
}
public void printCoordinates() { // just used for printing
System.out.println("x = " + x + " / y = "+ y);
}
}
Your Player class just need a minor adjustment to create proper Enemy classes:
Enemy[] enemy = new Enemy[3];
for(int i = 0; i < enemy.length; i++){
enemy[i] = new Enemy(canvas, context);
enemy[i].printCoordinates(); // just used for printing the generated coordinates
enemy[i].draw();
}
You just have to provide proper canvas and context instances for the new Enemy instance. You may also drop the context instance since you (currently) don't use it anythere in that class.
This is an example print of above code:
x = 27.236885 / y = 7.8905525
x = 61.842735 / y = 158.4654
x = 186.16629 / y = 20.208426
If you really want to extend the Player class, then you can still do that. This won't change much in your Enemy class.

Android tile based game

I develop tile based game to draw i use function canvas.drawBitmap() in each frame function drawBitmap using 400+ times when i use scroll (Gestures) performance is pretty bad.
Can anyone give me advice how to increase performance to make smooth animation.
public class DiamondIsometric implements Render{
private int MapWidth;
private int MapHeight;
private Bitmap _surface;
private Bitmap tempBitmap;
public DiamondIsometric(int MapWidth,int MapHeight,Bitmap _surface)
{
this.MapWidth=MapWidth;
this.MapHeight=MapHeight;
this._surface = _surface;
}
public MapObject[][] BuildMap()
{
int rx;
int ry;
MapObject[][] MapObjects = new MapObject[MapWidth][MapHeight];
for(int x=0;x<MapHeight;x++)
for(int y=0;y<MapWidth;y++)
{
rx=(x-y)*_surface.getWidth()/2;
ry=(x+y)*_surface.getHeight()/2;
MapObject temp = new MapObject(new Point(rx,ry),_surface);
MapObjects[x][y]=temp;
}
return MapObjects;
}
#Override
public void Render(Canvas canvas) {
}
#Override
public void Render(Canvas canvas,MapObject[][] MapObjects)
{
Paint temp = new Paint();
temp.setColor(Color.BLACK);
canvas.drawPaint(temp);
Bitmap toDraw = Bitmap.createBitmap(MapWidth*_surface.getWidth(), MapHeight*_surface.getHeight(), Config.RGB_565);
int bitmapOffsetX,bitmapOffsetY;
canvas.drawBitmap(this.Render2(canvas,MapObjects),0,0,null);
}
public Bitmap Render2(Canvas canvas, MapObject[][] MapObjects)
{
Paint temp = new Paint();
temp.setColor(Color.BLACK);
tempBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Config.RGB_565);
Canvas wideBMPCanvas = new Canvas(tempBitmap);
int bitmapOffsetX,bitmapOffsetY;
for(int i=0;i<MapObjects.length;i++)
for(int j=0;j<MapObjects[i].length;j++)
{
bitmapOffsetX=(IsometricView.globalAnchor.x % MapObjects[i][j]._bitmap.getWidth());
bitmapOffsetY=(IsometricView.globalAnchor.y % MapObjects[i][j]._bitmap.getHeight());
wideBMPCanvas.drawBitmap(MapObjects[i][j]._bitmap,MapObjects[i][j].coords.x-IsometricView.globalAnchor.x ,MapObjects[i][j].coords.y-IsometricView.globalAnchor.y , null);
}
return tempBitmap;
}
}
Use a game engine like andEngine or libgdx. They use OpenGL rendering which is usually much faster.
Update: If you want not to use OpenGL/game engines you should try to combine tiles into a larger bitmap. Create a larger bitmap and create a new canvas (new Canvas(largeBitmap)) to draw the tile to it. Drawing one larger is faster than drawing multiple smaller ones. For my Game K'UMPA I used a similar approach, which is more complex in detail, because only a small part of the map is visible on the screen.
Maybe you could try to not create a bitmap at each render call.
I assume that you're calling render for each frame:
public class DiamondIsometric implements Render {
private int MapWidth;
private int MapHeight;
private Bitmap _surface;
private Bitmap toDraw;
private Canvas wideBMPCanvas;
public DiamondIsometric(int MapWidth,int MapHeight,Bitmap _surface)
{
this.MapWidth = MapWidth;
this.MapHeight = MapHeight;
this._surface = _surface;
this.toDraw = null;
this.wideBMPCanvas = null;
}
public MapObject[][] BuildMap()
{
int rx;
int ry;
MapObject[][] MapObjects = new MapObject[MapWidth][MapHeight];
for(int x=0;x<MapHeight;x++)
for(int y=0;y<MapWidth;y++)
{
rx=(x-y)*_surface.getWidth()/2;
ry=(x+y)*_surface.getHeight()/2;
MapObject temp = new MapObject(new Point(rx,ry),_surface);
MapObjects[x][y]=temp;
}
return MapObjects;
}
#Override
public void Render(Canvas canvas) { }
#Override
public void Render(Canvas canvas,MapObject[][] MapObjects)
{
Paint temp = new Paint();
temp.setColor(Color.BLACK);
canvas.drawPaint(temp);
if (this.toDraw == null) {
this.toDraw = Bitmap.createBitmap(MapWidth*_surface.getWidth(), MapHeight*_surface.getHeight(), Config.RGB_565);
}
if (this.wideBMPCanvas == null) {
this.wideBMPCanvas = new Canvas(this.toDraw);
}
int bitmapOffsetX,bitmapOffsetY;
for (int i = 0; i < MapObjects.length; i++) {
for(int j = 0; j < MapObjects[i].length; j++)
{
bitmapOffsetX = (IsometricView.globalAnchor.x % MapObjects[i][j]._bitmap.getWidth());
bitmapOffsetY = (IsometricView.globalAnchor.y % MapObjects[i][j]._bitmap.getHeight());
this.wideBMPCanvas.drawBitmap(MapObjects[i][j]._bitmap, MapObjects[i][j].coords.x - IsometricView.globalAnchor.x,
MapObjects[i][j].coords.y - IsometricView.globalAnchor.y, null);
}
}
canvas.drawBitmap(this.toDraw, 0, 0, null);
}
}

Categories

Resources