Drawing image dynamically?


#1

Hey there, I’m working on a new plugin, and in the paint() method I draw an image loaded in the binary, that serves as the background image, using Graphics::drawImage. I’d like for this background image to be changed depending on certain circumstances (in this case, when a certain slider value is changed). How can I draw a new image as the background in this case? What I tried to do is call repaint() in the slider listener, and have the paint() method contain checks to decide which image to draw, but it seems repaint() doesn’t actually call paint(). I am unsure how to use the Graphics class outside of the paint() method. Thanks!


#2

It should. Reasons why it doesn’t could be

  1. The Component has zero size. It can only paint inside bounds, unless you set the flag Component::setPaintingIsUnclipped (true)
  2. The component is hidden behind an opaque component
  3. The message thread is blocked forever
  4. The component was not added via addAndMakeVisible

Usually you don’t. The Graphics class makes only sense with a context to draw on. either you get a Graphics object as argument from the paint call, or you create a Graphics on an Image. Then your drawing will appear only on that image. You cannot paint on the screen outside the paint method (exceptions are methods you call from inside the paint method providing the graphics object to the called method…)


#3

Hey thanks for the prompt response, it seems it’s actually something wrong with my code, the paint() calls a method I made containing a switch statement and for some reason it’s calling every case in the switch rather than just the int it checks, I have no idea why it’s doing this but once I fix this that should hopefully solve my problem.


#4

If you have a complex background you want for your Component and you don’t need it to be redrawn from scratch in your paint() method you can create a background Image and use that in your paint() method.

Something like:

void CMidiDisplayComponent::createNewBackground()
{
   m_GrooveBackground = Image (Image::RGB,
                           jmax (1, m_Background.getWidth()), jmax (1, m_Background.getHeight()),
                           true);

    Graphics g (m_GrooveBackground);    // m_GrooveBackground is a class Image member

    g.drawImageAt (m_Background, 0, 0);  // m_Background is a class Image member

    drawStaffLines (g);

    :

    repaint();
}

then

 void CMidiDisplayComponent::paint (Graphics& g)
{
    g.drawImageAt (m_GrooveBackground, 0, 0);
}

That way the background in this example only gets recalculated/redrawn when the groove’s length changes.

Rail


Slider keeps getting redrawn
#5

If you have a switch calling every case it sounds like you are just missing some break; statements.