如何设置我试图从左上角到左下角进入JLabel的组件的来源?

时间:2017-08-10 04:34:58

标签: java swing sprite jlabel

我试图制作2D精灵游戏,截至目前,图片绘制的JLabel从左上角开始。当我试图横向移动精灵时会出现这个问题,因为如果下一个精灵应该比之前更高,它就不会像现在这样站在地板上。在这张图片中,左边是起点,中间是它现在做的,左上角是0,0,右边是它应该是,从实际游戏中屏幕抓取。

下面是我对马里奥模型的描绘:

  public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(sprite, 0,0, null); 
  }

以下是我的paintComponent,它在一个类中运行时,将图像渲染到屏幕上:

  public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    marioSprite.paint(g2);
  }

以及如何从文件中提取图像:

 //generate URL
  public static URL urlGenerator(String name){
    URL u = lookup().lookupClass().getResource(name);
    return u;
  }

  //return image with filtered color
  public static BufferedImage generateAndFilter(BufferedImage b, URL u){

    try{
      b = ImageIO.read(u);
      int width = b.getWidth();
      int height = b.getHeight();
      int[] pixels = new int[width * height];
      b.getRGB(0, 0, width, height, pixels, 0, width); 
      for (int i = 0; i < pixels.length; i++) {

        if (pixels[i] == 0xFFff00fe) {
          pixels[i] = 0x00ff00fe; 
        }
      }
      BufferedImage newSprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      newSprite.setRGB(0, 0, width, height, pixels, 0, width);
      b = newSprite;
    } 
    catch(IOException e){
      System.out.println("sprite not found");
      e.printStackTrace();
    }
    return b;
  }    

Mario的每个实例都有一个精灵设置:

  public void setSprite(String spriteName){
    URL spriteAtLoc = Utils.urlGenerator(spriteName);
    this.sprite = Utils.generateAndFilter(sprite,spriteAtLoc);
    this.currentSpriteName = spriteName;
  }

enter image description here

0 个答案:

没有答案