Simplest way to draw an image with a hole in the center


#1

Hi, I would like to learn how to draw an image with circular hole in the center.
The circular area should be transparent.
What would be the simplest way to do this? Thanks!


#2

It is not clear what you specific case is, but you could use something as simple as a PNG with a transparent area. For something more flexible check out the examples, specifically examples/shaders/fboAlphaMask. This will let you draw pretty much anything with any part transparent.


#3

Thanks @fresla

I checked the fboAlphaMask example and modified the draw function as the following.
(Find the 2 areas where I commented with FULL CAPITAL letters.)

//--------------------------------------------------------------
void ofApp::draw(){

    backgroundFbo.begin(); //STORE BACKGROUND DRAWINGS INTO THE FBO!!!
    ofSetColor(255, 0, 0);
    ofDrawCircle(400, 300, 100);
    backgroundFbo.end();
    
    ofSetColor(255);

    //----------------------------------------------------------
    // this is our alpha mask which we draw into.
    if(bBrushDown) {
        maskFbo.begin();
        
        int brushImageSize = 50;
        int brushImageX = mouseX - brushImageSize * 0.5;
        int brushImageY = mouseY - brushImageSize * 0.5;
        brushImage.draw(brushImageX, brushImageY, brushImageSize, brushImageSize);
        
        maskFbo.end();
    }
    
    //----------------------------------------------------------
    // HERE the shader-masking happends
    fbo.begin();
    // Cleaning everthing with alpha mask on 0 in order to make it transparent by default
    ofClear(0, 0, 0, 0);
    
    shader.begin();
    // here is where the fbo is passed to the shader
    shader.setUniformTexture("maskTex", maskFbo.getTextureReference(), 1 );
    
//    backgroundImage.draw(0, 0);
    backgroundFbo.draw(0, 0); //DRAW THE BACKGROUND FBO!!!
    
    shader.end();
    fbo.end();
    
    //----------------------------------------------------------
    // FIRST draw the background image
    foregroundImage.draw(0,0);
    
    // THEN draw the masked fbo on top
    fbo.draw(0,0);
    
    //----------------------------------------------------------
    ofDrawBitmapString("Drag the Mouse to draw", 15,15);
    ofDrawBitmapString("Press spacebar to clear", 15, 30);
}

And here’s the result I got:

Is this the best solution or is there a simpler way to do it without having to write the background drawings to an FBO?


#4

Does this look like what you want? Draw the shape that you want to be transparent (your hole) in the mask part, you can do this with shaped like ofDrawCircle(10,10,10).

Otherwise just use the foreground and background images you want instead of the ones that are in the example.


#5

Yes, That’s what I want to do, make a hole in the center of the image.
Do you mean you know a simpler solution to do this?


#7

you can also just use texture.setAlphaMask(…) and pass an image with the mask