JuSchu
JuSchu

Reputation: 1490

getColorMode() in Processing

With

colorMode(HSB);
colorMode(RGB);

I can set the color mode. Apparently the function getColorMode() does not exist. Is there an other soloution to get the color mode? What I'm trying to do is something like this

int cMode = getColorMode();
colorMode(HSB);
// draw stuff
colorMode(cMode);

This code is inside of my class Track. I want to draw a recorded GPS track and the hue value should be controled by the speed or the elevation. Right now I set the color mode back to RGB after I finished drawing. Of course it would be better to set it back to the color mode it was before rather than just assuming, that it already was RGB.

Upvotes: 4

Views: 353

Answers (2)

Kevin Workman
Kevin Workman

Reputation: 42174

Let's take a look at the source for PApplet. That class contains this variable:

public PGraphics g;

And here is the colorMode() function:

public void colorMode(int mode) {
  if (recorder != null) recorder.colorMode(mode);
  g.colorMode(mode);
}

That tells us that PApplet#colorMode() is really just a shortcut to PGraphics#colorMode().

So let's look at the source for PGraphics. The colorMode() function from that class eventually leads here:

public void colorMode(int mode,
                        float max1, float max2, float max3, float maxA) {
    colorMode = mode;
    //more code

Which leads us to the colorMode variable:

/** The current colorMode */
public int colorMode; // = RGB;

In other words, to get to the current color mode, you have to go from PApplet to its g variable, to its colorMode variable. If you're in a sketch, it looks like this:

void setup() {
 size(500, 500);
 colorMode(HSB);
}

void draw() {

  background(0);

  if(g.colorMode == RGB){
    println("RGB");
  }
  else if(g.colorMode == HSB){
    println("HSB");
  }
}

If you aren't in a sketch, then you'll need to pass in the PApplet instance using the this keyword.

PApplet mySketch;
int colorMode = mySketch.g.colorMode;

Upvotes: 5

George Profenza
George Profenza

Reputation: 51857

In addition to Kevin's exhaustive answer, you can use pushStyle()/popStyle() calls to isolated drawing styles (including colour spaces):

void draw(){
  background(255);
  bars(HSB,0);
  bars(RGB,50);
}
void bars(int colorSpace,int y){
  pushStyle();
  colorMode(colorSpace);
  for(int i = 0 ; i < 10; i++){
    fill(i * 25,255,255);
    rect(10*i,y,10,50);
  }
  popStyle();
}

You can run a demo below:

function setup(){
  createCanvas(100,100);
}
function draw(){
  background(255);
  bars(HSB,0);
  bars(RGB,50);
}
function bars(colorSpace,y){
  push();
  colorMode(colorSpace);
  for(var i = 0 ; i < 10; i++){
    fill(i * 25,255,255);
    rect(10*i,y,10,50);
  }
  pop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.0/p5.min.js"></script>

Upvotes: 2

Related Questions