In this recipe, we will learn how to draw arbitrary shapes using the mouse.
We will begin a new contour every time the user presses the mouse button, and draw when the user drags the mouse.
The shape will be drawn using fill and stroke.
Include the necessary files to draw and create a ci::Shape2d
object.
Add the following code snippet at the top of your source file:
#include "cinder/gl/gl.h" #include "cinder/shape2d.h"
We will create a ci::Shape2d
object and create vertices using mouse coordinates. Perform the following steps to do so:
ci::Shape2d
object to define our shape and two ci::Color
objects to define the fill and stroke colors.Shape2d mShape; Color fillColor, strokeColor;
setup
method.We'll be using black for stroke and yellow for fill.
mFillColor = Color( 1.0f, 1.0f, 0.0f ); mStrokeColor = Color( 0.0f, 0.0f, 0.0f );
mouseDown
and mouseDrag
events.Declare the necessary callback methods.
void mouseDown( MouseEvent event ); void mouseDrag( MouseEvent event );
mouseDown
we will create a new contour by calling the moveTo
method.The following code snippet shows what the method should look like:
void MyApp::mouseDown( MouseEvent event ){ mShape.moveTo( event.getpos() ); }
mouseDrag
method we will add a line to our shape by calling the lineTo
method.Its implementation should look like the following code snippet:
void MyApp::mouseDrag( MouseEvent event ){ mShape.lineTo( event.getPos() ); }
draw
method, we will first need to clear the background, then set mFillColor
as the drawing color, and draw mShape
.gl::clear( Color::white() ); gl::color( mFillColor ); gl::drawSolid( mShape );
mStrokeColor
as the drawing color and draw mShape
as a stroked shape.gl::color( mStrokeColor ); gl::draw( mShape );
ci:Shape2d
is a class that defines an arbitrary shape in two dimensions allowing multiple contours.
The ci::Shape2d::moveTo
method creates a new contour starting at the coordinate passed as a parameter. Then, the ci::Shape2d::lineTo
method creates a straight line from the last position to the coordinate which is passed as a parameter.
The shape is internally tessellated into triangles when drawing a solid graphic.
It is also possible to add curves when constructing a shape using ci::Shape2d
.
3.139.97.202