Add PGraphics to a custom method

Hi All,
I’ve got this code:

void myrect(float xa,float ya,float xb,float yb){
  float x1=xa;
  if(xa>xb)  
  {
    while(xb<x1){
    x1--;
    point(x1,ya);
    point(x1,yb);
    }
  }
  else if(x1<xb){
    while(x1<xb){
    x1++;
    point(x1,ya);
    point(x1,yb);
  }
}
  if(ya>yb){
  while(ya>yb){
    ya--;
    point(xa,ya);
    point (xb,ya);
  }
}
if(ya<yb){
  while(ya<yb){
    yb--;
    point(xa,yb);
    point (xb,yb);
  }
}
}

This method is drawing a rectangle. -Yeah, I know, that there is a rect(), but it’s only allowed to use point() when I’m drawing a rect. So I would like to add a PGraphics to this function. How can I do it?

And how can I fill this rectangle? The fill() doesn’t work here…

Thanks!

Hello,

Here is how pg works - just add more points. Apply idea to your function myrect().

To fill the rect thing, try have one while loop B inside a while loop A in a way that

  • A goes over all lines (rows) and
  • B over all points (columns) in that row
    like in a grid.

Then use a point(B_value, A_value);.

Chrisir

//https://www.processing.org/reference/PGraphics.html


PGraphics pg;

void setup() {
  size(300, 400);

  pg = createGraphics(40, 40);

  pg.beginDraw();
  pg.background(100);
  pg.stroke(255);
  pg.point(13, 13);
  pg.point(22, 22);
  pg.endDraw();
}

void draw() {
  image(pg, 9, 30);
}
1 Like

Thanks, it looks like its working :smile:
Is it possible to fill everything outside the rectangle?
re

Fill the rectangle

To fill only the rectangle:

  • A must start at ypos from rect (its upper left corner) and go on until ypos + its height (e.g. 100) is reached
  • B must start at xpos of its upper left corner and go on until xpos plus it’s width is reached

Fill the entire screen

You can fill the entire screen with background(0); or whatever color. You can apply the above principle also (going from 0 to width of screen etc.).

[and don’t draw a point when its inside the inner rect, if you like. Use if…]

1 Like