Rectangular Button


#1

Hi, I am wondering what the simplest way to create rectangular buttons is. I tried making a new rectangle using ofRect but would like to make it clickable. Any suggestions?


#2

check if you mouse cursor is inside and ofGetMousePressed() is true

https://openframeworks.cc//documentation/types/ofRectangle/#!show_inside
https://openframeworks.cc//documentation/events/ofEvents/#!show_ofGetMousePressed


#3

Of you can use this code based on events that is very simple and rock solid.


#4

Thank you so much!


#5

hi @kgit
ofRect simply draws a rectangle. Also, it is a deprecated function and you should use ofDrawRectangle instead.
I think that the easiest way is to use an ofRectangle object.

Asuming that you are coding in ofApp.h and ofApp.cpp

in ofApp.h

class ofApp: public ofBaseApp{
//... what ever else you might have in this class
ofRectangle myRect;
bool bIsClicked = false;
};

in ofApp.cpp

void ofApp::setup(){

//leave what ever else you have here.
//set the position of your rectangle. you can change this at any point during the apps lifetime.
myRect.set(100,100, 500, 40); // x, y, width, height
}

void ofApp::draw(){
// leave whatever else you are drawing

if(bIsClicked){
ofSetColor(ofColor::yellow);// draw a yellow rectangle when clicked
}else{
ofSetColor(ofColor::gray);
}

ofDrawRectangle(myRect);

}
void ofApp::mousePressed(int x, int y, int button){
bIsClicked = myRect.inside(x,y);
}

hope this helps


Need help with mouse stuff