java - 理解 "Sprite' s onDraw()"方法时遇到问题

标签 java android sprite android-animation

 public class Sprite 
 {
   private static final int BMP_COLUMNS = 3;
   private static final int BMP_ROWS = 4;
   private int x= 0;
   private int y= 50;
   private int xSpeed= 5;
   private GameView gameView;
   private Bitmap bmp;
   private int width;
   private int height;
   private int currentFrame = 0;

 public Sprite(GameView gameView,Bitmap bmp)
  {
    this.gameView=gameView;
    this.bmp=bmp;
    this.width = bmp.getWidth()/BMP_COLUMNS;
    this.height = bmp.getHeight()/BMP_ROWS;
   }
 private void update()
 {
     if(x > gameView.getWidth() - width - xSpeed)
     {
         xSpeed = -5;
     }
     if(x + xSpeed<0)
     {
         xSpeed=5;
     }
     x = x + xSpeed;
     currentFrame = ++currentFrame % BMP_COLUMNS; <--how it works..?
    }

 public void onDraw(Canvas canvas)
      {
     update();
     int srcX = currentFrame*width; <---how it works..?
     int srcY = 2*height;   <-----how it works..?
     Rect src = new Rect(srcX,srcY,srcX+width,srcY+height);  <--how it works..?
     Rect dst = new Rect(x,y,x+width,y+height);  <----how it works..?
     canvas.drawBitmap(bmp,src,dst,null);        
     }
 }

最佳答案

源位图是 3*4 Sprite 图像的合成。 该 Sprite 在位图中使用 3 个不同的图像,代码将循环显示它们(图像 0、1 和 2)。

currentFrame = ++currentFrame % BMP_COLUMNS; <--how it works..?

currentFrame 将循环遍历值 1..BMP_COLUMNS-1,即 0, 1, 2, 0, 1, 2, ...

int srcX = currentFrame*width; <---how it works..?
int srcY = 2*height;   <-----how it works..?

查找要使用的图像的位置。对于这个特定的 Sprite ,有 3 个图像(可能几乎相同,区别可能是闪烁的灯光或类似的东西)。

Rect src = new Rect(srcX,srcY,srcX+width,srcY+height);  <--how it works..?

计算源位图中的位置。

Rect dst = new Rect(x,y,x+width,y+height);  <----how it works..?

计算显示器上的位置。

关于java - 理解 "Sprite' s onDraw()"方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7117575/

相关文章:

java - 小 LibGdx 加载文件时遇到问题

Java:如何确定文件所在的驱动器类型?

java - 有什么工具或技术可以以编程方式验证数据库之间的约束吗?

c++ - Ncurses : movement

javascript - 更改背景位置 : "x"px "x"px using jQuery/Javascript for a class 中的 "y"

java - 为什么 Weld 在 Tomcat 上显示 "Injection into Listeners is not supported"?

android - Java 8 New Date API 在 Android N 中可用吗?

java - 在 proguard android 中忽略警告是正确的

Android - 希望应用每秒执行一次任务

python - Pygame根据位置重叠 Sprite (绘制顺序)