How to draw shape clipped inside the other shape


#1

Hi, I wonder if there’s any solution to draw a shape clipped inside the other shape just like this image.
It is drawing an ofCircle in side ofRectRounded.
I used stencil buffer to do this but unfortunately, stencil doesn’t seem to work on mobile devices.
So I’m wondering if there’s other solution to do this. Thank you.


#2

Using shaders, draw your rounded rectangle and create a stencil map in an ofFbo, then with another shader you can choose to paint only where you have the stencil set (inside the rectangle).


#3

also, ofTexture has “setAlphaMask” where you can add a second texture that will be the alpha channel on the underlying texture, – in this case, the square could be an FBO and you could add an alpha mask for the rounded corners of the square. happy to make a small example if it helps.


#4

Thank you so much! I would really appreciate it :slight_smile:


#5

in h file:

ofFbo originalFbo;
ofFbo mask;

in cpp file

#include "ofApp.h"

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

    
    originalFbo.allocate(200,200);
    mask.allocate(200,200);
    
    mask.begin();
    ofClear(0,0,0);
    ofSetColor(255);
    ofDrawRectRounded( 0,0,200,200, 50);
    mask.end();
    
    
    
    
}

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

    
    originalFbo.begin();
    ofClear(0,255,0, 255);
    ofSetColor(255,0,0);
    ofCircle(100 + 100 * sin(ofGetElapsedTimef()), 100, 50);
    originalFbo.end();
    
}

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

    
    mask.draw(0,0);
    
    // disable the alpha mask to see what this FBO looks like unmasked
    originalFbo.getTexture().disableAlphaMask();
    originalFbo.draw(300,0);
    
    
    originalFbo.getTexture().setAlphaMask(mask.getTexture());
    originalFbo.draw(600,0);
    
    
}

output:


#6

Wow. That’s exactly what I wanted to achieve.
I learned a lot from your code. Thank you so much Zach!