选择图像并创建对象。处理2.0

时间:2015-04-20 17:32:24

标签: image oop processing draw

这是我的Image类的代码片段:

class Image{

  public int width;
  public int height;

  public PImage img;

  Image(PApplet parent){

    width = 512;
    height = 512;

    img = new PImage();
    img = parent.loadImage("test.jpg");
    img.resize(width, height);
  }
}

我以这种方式在主文件中绘制它:

image(image.img, 287, 280);

我想选择点击它的图片:

void mousePressed() {
   if (gui.btnOver1) {
     selectInput("Choose file:", "fileSelected");
   }
}

但是,我不知道如何以OOP方式使用此功能:

void fileSelected(File selection) {
  if (selection == null) {
    println("Window was closed or the user hit cancel.");
  } else {
    img = loadImage(selection.getAbsolutePath());
    img.loadPixels();
  }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:-1)

如何为您的班级添加方法如下:

class Image{

  public int width;
  public int height;

  public PImage img;

  Image(PApplet parent){

      width = 512;
      height = 512;

     img = new PImage();
     img = parent.loadImage("test.jpg");
     img.resize(width, height);
  }

   public void loadNew(path){
      img = loadImage(path);
     // I don't think you need to .updatePixels() after .loadImage()
   }
}

然后你就这样使用它:

void fileSelected(File selection) {
  if (selection == null) {
    println("Window was closed or the user hit cancel.");
  } else {
     // assuming you have an 'image' object of the type Image
     image.loadNew(selection.getAbsolutePath());
  }
}

注意: 我写了最后一行处理代码已经有一段时间了,它可能有点不对,但它应该回答你的问题

您甚至可以使用函数绘制Image对象,而不是调用img的属性image, 那样:

// a method of your class
public void draw(int x, int y){
  image(img, x, y);
}

然后在主draw()内,您将调用

// always your image object here
image.draw(20, 34);

我希望它有所帮助!