How to use graphics outside of Component::Paint()?


#1

Hi.

I'd like to draw some things in a method other than Component::Paint()

I've tried the following as a test but it doesn't display anything.

Can you explain what's wrong ?

void MainContentComponent::drawBridge(...){

    Image image(Image::RGB, 1000, 1000, true);
    Graphics g(image);
    g.setColour(Colour(200, 200, 200));
    g.fillAll();
    
}

#2

An Image just creates memory that can be drawn to.  A Graphics object just provides the means to draw into that memory.  You can draw into an image at any time, but to get it on the screen you'd then need to call drawImage in the paint method using the graphics that's passed into that.

 

void customImageDrawMethod() {
   
   Graphics g(yourImage);
   ...do drawing...

}


void paint(Graphics & g) {
    g.drawImage(yourImage, ...);
}

 

 


#3

May I use another class method that would return an ImageComponent so that the component which calls it would be able to display it ?


ImageComponent* BridgeGraphicHandler::returnImage()
{

    ImageComponent* image = new ImageComponent;
    
    Path path = figureOutPath();
    
    Image bitmap(Image::RGB, 500, 500, true);

    Graphics g(bitmap);
    g.setColour(Colour(255, 0, 0));
    g.strokePath(path, PathStrokeType(2.0f));

    image->setImage(bitmap);
    image->paint(g);

    return image;

}

 

Then I have this in the calling method

image = bridgeGraphicHandler.returnImage();
addAndMakeVisible(image);

But it doesn't yield any display.


#4

In your component which holds the image componen, you'd need to set the bounds:

void YourComponent::resized()

{

    image->setBounds(0, 0, getWidth(), getHeight()); // or where ever you want the image to be...

}


#5

Thank you