Drawing a rectangle without using rects();

edited November 2017 in Questions about Code

Hey everyone! I really need help with this task. I need to draw a rectangle without using the function rect() but by creating my own function, which I've been trying to do but it just doesn't work. Could anyone help me with this please? This is my code:

PImage img;
color c = color(random(255), random(255), random(255));

void setup() { 
  size(400, 400);
  img = createImage(400, 400, RGB); 
  img.loadPixels();
  img.updatePixels();
  image(img, 0, 0);
}

void draw() {
  myRectangle(10, 10, 40, 50);
}

void myRectangle(int xPos, int yPos, int widthRect, int heightRect) {
  img.loadPixels();
  for (int y = yPos; y < yPos + heightRect; y++) {
    for (int x = yPos; x < xPos + widthRect; x++) {
      img.set(y*width, x, c);
    }
  }
  img.updatePixels();
}
Tagged:

Answers

  • img.set(y*width, x, c);

    why y * width?

    set looks like this, set(x, y, c) which sets the pixel at x, y to colour c

    https://processing.org/reference/set_.html

    BUT your use of loadPixels and updatePixels looks like your trying to use the pixels array directly, which is just

    img.pixels[y * width + x] = c;
    

    you are confusing two different things.

    see this tutorial - https://processing.org/tutorials/pixels/

    specifically the "Example: Setting Pixels according to their 2D location", specifically the use of loc, which is your equation above.

  • I actually don't want to use Pixels I have to do it with img..

  • img has a pixel array too. img.pixels[] like you have there... replace line 20 with

    img.pixels[y * width + x] = c;
    

    see if that works (i can't test it here)

  • @misus -- Are you allowed to use line(), or should it only be done with set()?

  • I'm not allowed to use line()

  • As koogs pointed out you have made a mistake in line 20. The variables x and y hold the actual location for the pixel to update so change it to

    img.set(x, y, c);

    Also you are not drawing the image in the draw() method so copy or move line 9 inside the draw() method.

Sign In or Register to comment.