Set Application With and Height in Size() Based on the Background Image Width and Height

edited January 2015 in How To...

Say have a background image named img. I get exceptions when I do : size(int(img.width), int(img.height));

Is there a way I can automatically set the size of the application window based on the background image W and H?

FYI, background is a PShape stored in an SVG file.

Tagged:

Answers

  • Works fine for me...

    PImage img = loadImage("http://www.gravatar.com/avatar/8436b2ef98da12c6fd78d4fe0ea56eee?size=250&default=http://vanillicon.com/8436b2ef98da12c6fd78d4fe0ea56eee_200.png");
    void setup(){
      size(img.width, img.height);
    }
    void draw(){
      image(img,0,0);
    }
    
  • Thanks TfGuy44 but that doesn't work. I think for the background I should not be using PShape and must use PImage instead!

  • Works fine for me... Uses the bot1.svg that comes with Examples > Basics > Shape > LoadDisplaySVG

    PShape bot;
    
    void setup() {
      bot = loadShape("bot1.svg");
      size(int(bot.width), int(bot.height));
    } 
    
    void draw(){
      background(102);
      shape(bot, 0, 0);
    }
    
  • OK it works now. Thanks for the tip!

  • edited January 2015

    Just an extra caution: Processing re-runs the code above size(). @-)
    In order to avoid re-loading files unnecessarily, check whether it's still null: *-:)

    // forum.processing.org/two/discussion/9205/
    // set-application-with-and-height-in-size-
    // based-on-the-background-image-width-and-height
    
    static final String SVG = "https://" + "upload.wikimedia.org/"
    + "wikipedia/commons/8/84/Example.svg";
    
    static final String RENDERER = JAVA2D;
    //static final String RENDERER = P2D;
    
    PShape bg;
    
    void setup() {
      if (bg == null)  bg = loadShape(SVG);
      size((int) bg.width, (int) bg.height, RENDERER);
      noLoop();
    }
    
    void draw() {
      background(0300);
      shape(bg);
    }
    
  • edited January 2015

    Alternatively we can check either width or height are still set to their initial default values: O:-)
    if (width == DEFAULT_WIDTH) bg = loadShape(SVG);

Sign In or Register to comment.