Wrong Text Rasterization Position on Mac

I wrote a sketch that is supposed to rasterize text placed on a PGraphics object and display it centered on the canvas. However, in practice, the rasterized text appears in the bottom right corner instead of the center.

I double-checked: the text without the rasterization effect is perfectly centered.
Interestingly, the exact same code works as expected on Windows, but shows this misalignment issue on macOS, which leads me to believe it might be OS-related.

Could someone help me figure out what’s causing this and how to fix it?

Code:

import controlP5.*;

ControlP5 cp5;
PImage img;
int res = 50;
int levels = 5;
PGraphics pg;

void setup() {
  size(600, 600);
  cp5 = new ControlP5(this);
  colorMode(HSB, 360, 100, 100);
  noStroke();
  imageMode(CENTER);

  cp5.addSlider("res")
    .setPosition(20, 20)
    .setRange(5, 100)
    .setValue(res)
    .setSize(200, 20);

  cp5.addSlider("levels")
    .setPosition(20, 50)
    .setRange(2, 10)
    .setValue(levels)
    .setNumberOfTickMarks(10)
    .setSize(200, 20);
    
    
  pg = createGraphics(600, 600);
}

void draw() {
  background(360);

  res = int(cp5.getController("res").getValue());
  levels = int(cp5.getController("levels").getValue());

  int step = width / res;
  
  pg.beginDraw();
  pg.pushMatrix();
  pg.translate(width/2, height/2);
  pg.colorMode(HSB, 360, 100, 100);
  pg.background(200);
  pg.fill(0);
  pg.textAlign(CENTER, CENTER);
  pg.textSize(32);
  pg.text("Tec Inter", 0, 0);
  pg.popMatrix();
  pg.endDraw();

  img = pg.get();

  for (int y = 0; y < height; y += step) {
    for (int x = 0; x < width; x += step) {
      color c = img.get(x, y);
      float b = brightness(c);
      if (b < 100) {
        fill(0);
        float r = width/res;
        r = map(b, 100, 0, r/levels, r);
        ellipse(x + step / 2, y + step / 2, r, r);
      }
    }
  }
  
  //image(pg,width/2,height/2);
}

void keyPressed() {
  if (key == ' ') {
    saveFrame("raster_output_####.png");
  }
}

The problem appears to be the macs hires display change the beginning of your setup function to

void setup() {
  size(600, 600);
  pixelDensity(1);

Also I suggest that you avoid creating the text image in the draw() method because this is done every frame i.e. 60 times a second. Rather create once in the setup method and just use it in draw

EDIT: Not a perfect solution since it very much depends on the font size. Try 160 instead of 32

3 Likes

Thanks so much! It works now