2012年2月26日 星期日

HW04-1


In this homework, I learned how to use text related functions. I used save() function to save the drawing board. But I haven't figured out how to save just the drawing (not included the buttons) yet. In fact, I used Save button to save this photo and uploaded it here.
Similar to the previous homework, I also created a custom class for TextButton.
Below is the source code for class TextButton:

class TextButton {
  int x, y; // The x- and y-coordinates
  int w; // Dimension (width and height)
  int h;
  color baseColor; // Default gray value
  color pressColor; // Value when mouse is over and pressed
  boolean over = false; // True when the mouse is over
  boolean pressed = false; // True when the mouse is over and pressed
  String textOnButton = "";

  TextButton(int xp, int yp, int wi, int hi, color b, color p, String t) {
    x = xp;
    y = yp;
    w = wi;
    h = hi;
    baseColor = b;
    pressColor = p;
    textOnButton = t;
  }
  // Updates the over field every frame
  void update() {
    if ((mouseX >= x) && (mouseX <= x+w) &&
      (mouseY >= y) && (mouseY <= y+h)) {
      over = true;
    } 
    else {
      over = false;
    }
  }
  boolean press() {
    if (over == true) {
      pressed = true;

      if (textOnButton.equals("Clear")) {
        background(255);
      }
      else if (textOnButton.equals("Save")) {
        save("D:\\test.jpg");
      }
      else if (textOnButton.equals("Eraser")) {
        selectedColor = 255;
      }
      else if (textOnButton.equals("+")) {
        selectedStrokeWeight+=1;
        strokeWeight(selectedStrokeWeight);
      }
      else if (textOnButton.equals("-")) {
        if (selectedStrokeWeight >=1)
          selectedStrokeWeight-=1;
        strokeWeight(selectedStrokeWeight);
      }

      return true;
    } 
    else {
      pressed = false;
      return false;
    }
  }
  void release() {
    pressed = false; // Set to false when the mouse is released
  }
  void display() {
    if (pressed == true) {
      fill(pressColor);
    } 
    else {
      fill(baseColor);
    }

    strokeWeight(1);
    stroke(0);
    rect(x, y, w, h);

    fill(0);
    textSize(10);
    float tw = textWidth(textOnButton);
    text(textOnButton, x + abs(tw - 40)/2, y+25);
  }
}

沒有留言:

張貼留言