Friday, February 22, 2019

Random icon position in canvas

We want an icon in canvas has random position when appear.
Copy in to onDraw.
Random generato = new Random();
int so = generato.nextInt(3);
Paint paint = new Paint();
paint.setTextSize(45);
paint.setColor(Color.parseColor("#FF00FF"));
canvas.drawText(so+"", r/2, 100, paint);
Run to see number from 0 to 2 appear. Random generate number from 0 to nextInt, we use these number set position to icon.

We have an icon name smile run pass over screen width.


If we random y index, it will appear in any position along with screen height.
Add to if command.
Random generato = new Random();
y = generato.nextInt(c) – smile.getHeight();

Now icon has random position.
If we want icon has another face when reappear, use Random like this.
Random generato = new Random();
int number = generato.nextInt(3);
switch (number){
     case 0:
     smile = BitmapFactory.decodeResource
      (this.getResources(), R.drawable.smile1);
     break;
     case 1:
     smile = BitmapFactory.decodeResource
      (this.getResources(), R.drawable.smile2);
     break;
     case 2:
     smile = BitmapFactory.decodeResource
      (this.getResources(), R.drawable.smile3);
     break;
}
Add to if command.
if(x>r){
x=- smile.getWidth();
Random generato = new Random();
y = generato.nextInt(c) - smile.getHeight();
Random generato2 = new Random();
int number = generato2.nextInt(3);
switch (number){
case 0:
smile = BitmapFactory.decodeResource
      (this.getResources(), R.drawable. smile);
break;
case 1:
smile = BitmapFactory.decodeResource
      (this.getResources(), R.drawable. smile2);
break;
case 2:
smile = BitmapFactory.decodeResource
      (this.getResources(), R.drawable. smile3);
break;
}
}

Run to see result.

No comments:

Post a Comment