Graphics

Reference ❯ Drawing Shapes, Styles and Positioning

Overview

How Codea Draws top ↑

When you begin a new project in Codea you'll notice that it consists of a tab called Main and some template code. Your project can consist of several tabs, the initial one is always called Main. If you add more files they will be listed across the top.

function setup()
    print(\"Hello World!\")
end

function draw()
    background(0,0,0)

    -- Do your drawing here
end

This is the framework that your project will use to run. There are two functions defined for you initially: setup() and draw().

setup() and draw() are executed by Codea when you press the play button to run your project. The setup() function is called once, at the start, and then the draw() function is called repeatedly (60 times per second, to be exact). In setup() Codea expects you to set up your initial program state, and in draw() you can tell Codea to render graphics onto the screen, update your program state over time, and so on.

In the next two sections we will cover these functions in detail.

The draw() function top ↑

When you press the play button, the draw() function is repeatedly executed by Codea. Codea tries to execute the draw() function 60 times per second - if it can. Codea can't guarantee that your draw() function will be called 60 times per second (it may slow down if your project performs a lot of computation, or creates highly complex drawing).

function draw()
    -- Set the background color to blueish
    background(100,120,180)

    -- Set the fill color to red
    fill(255,0,0)

    -- Set a wide outline
    strokeWidth(5)

    -- Set the outline color to white
    stroke(255)

    -- Draw a red circle with a white outline
    -- In the center of the screen
    ellipse( WIDTH/2, HEIGHT/2, 200 )
end

Note that the above code will run 60 times every second. That is, you are telling Codea to paint the background blue and draw a red circle with a white outline 60 times per second, from scratch. It does this so that you can create smooth motion by changing your program state over time, and updating your drawing code to reflect the new state. For example, you might make the circle bounce on the ground by changing its Y-position (the second parameter to ellipse()) every frame.

The setup() function top ↑

When you press the play button Codea will call the setup() function once, before it begins calling the draw() function. In here you can perform any once-off computations, set up program state, set the display mode, and do things that you don't need to do every frame. For example, the setup() function below creates a global variable controlled by a slider. This variable is then used in the draw() function to control the Y-position of a circle.

function setup()
    displayMode(STANDARD)
    parameter("YPosition", 0, 
              HEIGHT, HEIGHT/2)
end

function draw()
    background(0)
    fill(255,0,0)
    ellipse( WIDTH/2, 
             YPosition, 
             200 )
end

Drawing

background( red, green, blue ) top ↑

Syntax

background( gray )
background( gray, alpha )
background( red, green, blue )
background( red, green, blue, alpha )
background( color )

Clears the background to the specified color. You should generally call this at the start of your draw() function in order to clear the contents of the previous frame.

gray

int from 0 to 255, specifies value between white and black

alpha

int from 0 to 255, specifies opacity of the background

red

int from 0 to 255, specifies red amount of the background

green

int from 0 to 255, specifies green amount of the background

blue

int from 0 to 255, specifies blue amount of the background

color

a value of the color datatype

Examples

function draw() -- Dark blueish background background(0, 50, 70) -- Do some drawing end

ellipse( x, y, width, height ) top ↑

Syntax

ellipse( x, y, diameter )
ellipse( x, y, width, height )      

Draws an ellipse centered at x, y with horizontal and vertical dimensions specified by width and height. The ellipseMode() function sets how these parameters are interpreted. Use fill() to set the color of an ellipse and stroke() to set its outline color.

If only the width is specified, this is treated as the ellipse diameter (or radius, if ellipseMode( RADIUS ) is used).

The interpretation of an ellipse's x, y, width and height parameters can be specified using the ellipseMode() function. ellipseMode() is set to CENTER by default.

x

x-coordinate of the ellipse

y

y-coordinate of the ellipse

width

width of the ellipse

height

height of the ellipse

rect( x, y, width, height ) top ↑

Syntax

rect( x, y, width, height )

Draws a rectangle with its lower-left corner positioned at x, y and sized at width, height. Use fill() to set the color of a rectangle and stroke() to set the outline color.

The interpretation of a rectangle's x, y, width and height parameters can be specified using the rectMode() function. rectMode() is set to CORNER by default.

x

x-coordinate of the lower-left corner

y

y-coordinate of the lower-left corner

width

width of the rectangle

height

height of the rectangle

sprite( name, x, y ) top ↑

Syntax

sprite( name, x, y )
sprite( name, x, y, width )
sprite( name, x, y, width, height )

sprite( image, x, y )
sprite( image, x, y, width )
sprite( image, x, y, width, height )      

Draws the sprite specified by name. A sprite is a a bitmap graphic (such as a character, or a space ship). The name of the sprite specifies both the sprite pack and sprite to use.

Alternatively, an image can be provided in instead of a name to draw that image. CAMERA may also by provided in order to draw the current capture source video input.

By default the x and y parameters set the location of the center of the sprite, the origin mode can be set using the spriteMode() function. The last two parameters are optional and set the width and height in pixels, if these are not specified the sprite will be rendered at the pixel dimensions of its graphic. Sprites can be tinted with the tint() function.

name

name of the sprite to use, in the following format: "SpritePack:SpriteName" or CAMERA

image

image to draw onto the screen

x

x-coordinate of the center of the sprite (this can be changed with spriteMode)

y

y-coordinate of the center of the sprite (this can be changed with spriteMode)

width

optional width of the sprite in pixels

height

optional width of the sprite in pixels. If width is specified and height is not, then height is automatically computed to preserve the aspect ratio of the image.

Examples

background(127, 127, 127, 255) sprite("Planet Cute:Character Boy", WIDTH / 2, HEIGHT / 2)
background(127, 127, 127, 255) tint(255, 0, 0) sprite("Planet Cute:Character Boy", WIDTH / 2, HEIGHT / 2)
sprite(CAMERA, 0, 0)

text( string, x, y ) top ↑

Syntax

text( string, x, y )

Draws text at the given x, y location. You can set the font used by text() with the font() function. Text appearance can be further configured by using the fontSize() and fill() functions.

You can change the alignment and wrapping of text by using textAlign() and textWrapWidth(). If textWrapWidth() is set to 0 (the default) text will be drawn on one line. If textWrapWidth() is set to a value greater than 0 the text will word-wrap if it exceeds the width specified by textWrapWidth()

By default the x and y parameters set the location of the center of the text, the origin mode can be set using the textMode() function. Text color can be changed with the fill() function.

If you need to get the dimensions of a string in the current style, see the textSize function documentation.

string

the text string that you would like to draw onto the screen

x

x-coordinate of the center of the text (this can be changed with textMode)

y

y-coordinate of the center of the text (this can be changed with textMode)

Examples

background(100, 120, 160) font("Georgia") fill(255) fontSize(20) textWrapWidth(70) text("Hello World!", WIDTH/2, HEIGHT/2)

line( x1, y1, x2, y2 ) top ↑

Syntax

line( x1, y1, x2, y2 )

Draws a line between the two points specified by x1,y1 and x2,y2. A line's color can be set with the stroke() function and its width can be set with the strokeWidth() function. A line's cap style can be changed with the lineCapMode() function. Note that line cap modes only take effect when drawing with the rendering mode set to smooth(). When using noSmooth(), lines will be rendered using square end caps.

x1

x-coordinate of the first point

y1

y-coordinate of the first point

x2

x-coordinate of the second point

y2

y-coordinate of the second point

Examples

function draw() background(128) stroke(255) line(10, 10, 80, 80) end

Transform

translate( x, y ) top ↑

Syntax

translate( x, y )
translate( x, y, z )

Translates all subsequent drawing operations by the specified x and y values. Translations are cumulative, so a call to translate( 50, 0 ) followed by a call to translate( 10, 10 ) will translate all subsequent drawing operations by 60, 10. Translate can take an optional z parameter to specify depth.

x

amount of horizontal translation, in pixels

y

amount of vertical translation, in pixels

z

amount of depth translation, in pixels

rotate( angle ) top ↑

Syntax

rotate( angle )
rotate( angle, x, y, z )

Specifies an amount of rotation (in degrees) to apply to all subsequent drawing. All subsequent drawing functions will be rotated by angle value specified in this function. Rotations are cumulative, so calling rotate(30) followed by rotate(20) has the same effect as rotate(50).

rotate() can also be called with a specific axis, defined by the x, y, z parameters. This allows rotation to occur on an arbitrary axis for 3D effects. By default the axis is (0, 0, 1), this means that objects rotate about the axis pointing toward the viewer.

angle

amount of rotation in degrees

x

float, x value for the axis of rotation

y

float, y value for the axis of rotation

z

float, z value for the axis of rotation

scale( x, y ) top ↑

Syntax

scale( amount )
scale( x, y )
scale( x, y, z )     

Specifies an amount of scale to apply to all drawing. All subsequent drawing functions will be scaled by the x and y values specified in this function. Scale values are specified as a scalar multipliers, for example, scale(2.0, 2.0) will double the x and y dimensions of subsequent drawing commands. scale() is cumulative, so calling scale(0.5) followed by scale(0.5) will scale all subsequent drawing operations by 0.25 (i.e., one quarter of their original size).

amount

uniform amount of scale to apply horizontally and vertically. Applies on all axis, x, y and z.

x

amount of scale to apply on the x axis (horizontal)

y

amount of scale to apply on the y axis (vertical)

z

amount of scale to apply on the z axis (depth)

zLevel( z ) top ↑

Syntax

zLevel( z )

Sets the z level of future drawing operations. Negative values mean the drawing will occur behind (further into the screen), positive values will cause drawing to happen in front. By default all drawing will occur above previous drawing operations.

This property is pushed onto the matrix stack with pushMatrix().

z

float, the amount of depth for future drawing operations, use positive values to draw in front, and negative values to draw behind.

Advanced Transform

perspective( fov, aspect, near, far ) top ↑

Syntax

perspective()
perspective( fov )
perspective( fov, aspect )
perspective( fov, aspect, near, far )

Sets the projection matrix to the perspective projection defined by the parameters fov (field of view, in degrees), aspect (aspect ratio of the screen, defaults to WIDTH/HEIGHT), near and far. The near and far values specify the closest and farthest distance an object can be without being clipped by the view frustum.

When called without arguments, sets up a perspective projection with a field of view of 45 degrees and an aspect ratio of WIDTH/HEIGHT.

fov

float, field of view in degrees

aspect

float, aspect ratio of the screen. Defaults to WIDTH/HEIGHT

near

float, near clipping plane, defaults to 0.1

far

float, far clipping plane, default value is computed based on the height of the screen

ortho( left, right, bottom, top ) top ↑

Syntax

ortho()
ortho( left, right, bottom, top )
ortho( left, right, bottom, top, 
                      near, far )

Sets the projection matrix to the orthographic projection defined by the parameters left, right, bottom, top, near and far. The near and far values specify the closest and farthest distance an object can be without being clipped by the view frustum.

When called with no arguments, sets up the default orthographic projection, equivalent to ortho( 0, WIDTH, 0, HEIGHT, -10, 10 ).

left

float, left edge of the frustum

right

float, right edge of the frustum

bottom

float, bottom edge of the frustum

top

float, top edge of the frustum

camera(eyeX,eyeY,eyeZ, cX,cY,cZ, upX,upY,upZ) top ↑

Syntax

camera( eyeX, eyeY, eyeZ,
        centerX, centerY, centerZ,
        upX, upY, upZ )

Sets the view matrix to the simulate a camera positioned at eye and looking at center. With an up-vector specified by up.

This can be used in conjunction with the perspective projection to simulate a camera positioned in 3D space looking at your scene.

eyeX/Y/Z

floats, position of the "eye" in 3D

centerX/Y/Z

floats, coordinate to look at

upX/Y/Z

floats, up-vector of the camera, defaults to (0, 1, 0)

applyMatrix( matrix ) top ↑

Syntax

applyMatrix( matrix )

Multiplies the matrix specified by matrix against the current model matrix. The current model matrix represents the world transform, this is the same matrix used in pushMatrix and popMatrix operations.

matrix

matrix, the transformation to multiply against the current world transform

modelMatrix() top ↑

Syntax

modelMatrix()
modelMatrix( matrix )

When called with no arguments, returns a matrix containing current world transformation. When called with a matrix argument, sets the current world transformation to the given matrix.

matrix

matrix, the transformation to set as the current world transform

Returns

The current model matrix when called with no arguments

viewMatrix() top ↑

Syntax

viewMatrix()
viewMatrix( matrix )

When called with no arguments, returns a matrix containing current view transformation. When called with a matrix argument, sets the current view transformation to the given matrix.

The view transform defaults to the identity matrix and is provided as a convenient place to store a camera transform when dealing with 3D scenes. Standard Codea projects do not normally utilise it. See the camera() function for a convenient way to set up the view transform.

matrix

matrix, the transformation to set as the current view transform

Returns

The current view matrix when called with no arguments

projectionMatrix() top ↑

Syntax

projectionMatrix()
projectionMatrix( matrix )

When called with no arguments, returns a matrix containing current projection transformation. When called with a matrix argument, sets the current projection transformation to the given matrix.

The projection transform defaults to an orthographic projection the width and height of the screen. See the perspective and ortho functions for more advanced ways to set up the projection matrix.

matrix

matrix, the transformation to set as the current projection transform

Returns

The current projection matrix when called with no arguments

Style

color top ↑

Syntax

color.r
color.g
color.b
color.a
myColor = color( 255, 0, 0, 255 ) --red

This type represents a color with transparency information. You can provide this type as arguments to the style functions fill(), tint(), stroke(), and background().

r

int, the red component of this color from 0 to 255

g

int, the green component of this color from 0 to 255

b

int, the blue component of this color from 0 to 255

a

int, the alpha component of this color from 0 to 255

Examples

--Fill with red c = color( 255, 0, 0 ) fill( c )

color.blend( c ) top ↑

Syntax

c1 = color( 0, 0, 0, 128 )
c2 = color( 255, 255, 255, 255 )
c3 = c1:blend( c2 )

This method computes a color by blending two color types. Colors are blended based on the first color's alpha value. The blend amount is determined by the alpha value of the color invoking this method.

c

color, compute the blending between this color and c

Returns

Color computed by blending this color and c

color.mix( c, amount ) top ↑

Syntax

c1 = color( 255, 0, 0, 255 )
c2 = color( 0, 255, 0, 255 )
c3 = c1:mix( c2, 0.5 )

This method computes a color by mixing two color types linearly. Colors are blended based on the specified mix value, amount. A value of 0.5 for amount will generate a color that is half way between the two input colors.

c

color, compute the mixing between this color and c

amount

scalar, amount of contribution from either color. A value of 0.0 will result in the starting color, and 1.0 will result in the destination color.

Returns

Color computed by mixing this color and c by amount

blendMode( MODE ) top ↑

Syntax

blendMode()
blendMode( NORMAL | ADDITIVE | MULTIPLY )
blendMode( srcFactor, destFactor )
blendMode( srcFactor, destFactor,
           srcAlpha, destAlpha )

Sets the blend mode for all further drawing. The blend mode decides how new drawing operations are blended with underlying pixels.

The default blend mode is blendMode( NORMAL ), this blends graphics according to their alpha value. NORMAL will cause drawing operations to replace the underlying pixels where the alpha value is 1.0, and mix with the underlying pixels where alpha is less than 1.0.

ADDITIVE blend mode blends drawing operations by adding color. Using this mode will cause overlapping drawing to tend towards white. This allows for glowing effects, and is useful for particle rendering (e.g. sparks, glows, fire).

MULTIPLY blend mode blends drawing operations by multiplying color. Using this mode will cause overlapping drawing to tend towards black.

More advanced blend modes can be set up by using the advanced two and four parameter versions of the function. Advanced blend modes parameters are similar to the OpenGL functions glBlendFunc and glBlendFuncSeparate.

Calling blendMode() with no arguments will return the current blend mode (multiple values will returned if an advanced blend mode is set, up to four values can be returned).

mode

either NORMAL, MULTIPLY or ADDITIVE

NORMAL: specifies normal alpha-based blending

MULTIPLY: specifies multiplicative blending

ADDITIVE: specifies additive blending

srcFactor

ZERO ONE DST_COLOR ONE_MINUS_DST_COLOR SRC_ALPHA ONE_MINUS_SRC_ALPHA DST_ALPHA ONE_MINUS_DST_ALPHA SRC_ALPHA_SATURATE

destFactor

ZERO ONE SRC_COLOR ONE_MINUS_SRC_COLOR SRC_ALPHA ONE_MINUS_SRC_ALPHA DST_ALPHA ONE_MINUS_DST_ALPHA

srcAlpha

When this parameter is used, the factor specified for srcAlpha will be used to determine how to calculate the alpha value of the source fragment.

destAlpha

When this parameter is used, the factor specified for destAlpha will be used to determine how to calculate the alpha value of the destination fragment.

Returns

The current blend mode if called without arguments (up to four values can be returned). Returns nothing if called with arguments.

ellipseMode( MODE ) top ↑

Syntax

ellipseMode()
ellipseMode(CENTER|RADIUS|CORNER|CORNERS)

Sets the origin of the ellipses drawn with the ellipse() function. The default is ellipseMode( CENTER ).

mode

either CENTER, RADIUS, CORNER or CORNERS

CENTER: x, y specifies the center of the ellipse, w, h specify its x and y diameter.

RADIUS: x, y specifies the center of the ellipse, w, h specify its x and y radius.

CORNER: x, y specifies the lower left corner of the ellipse, w, h specify the size its x and y diameter.

CORNERS: x, y sets the lower left coordinate of the ellipse's bounding box. w, h sets the upper right coordinate of the ellipse's bounding box.

Returns

The current ellipse mode if called without arguments. Returns nothing if called with arguments.

rectMode( MODE ) top ↑

Syntax

rectMode()
rectMode(CENTER|RADIUS|CORNER|CORNERS)

Sets the origin of the rectangles drawn with the rect() function. The default is rectMode( CORNER ).

mode

either CENTER, RADIUS, CORNER or CORNERS

CENTER: x, y specifies the center of the rectangle, w, h specifies the rectangle's width and height.

RADIUS: x, y specifies the center of the rectangle, w, h specifies half the rectangle's width and height.

CORNER: x, y specifies the lower left corner of the rectangle, w and h specify the rectangle's width and height.

CORNERS: x, y sets the lower left coordinate of the rectangle's bounding box. w, h sets the upper right coordinate of the rectangle's bounding box.

Returns

The current rect mode if called without arguments. Returns nothing if called with arguments.

spriteMode( MODE ) top ↑

Syntax

spriteMode()
spriteMode( CENTER|RADIUS|CORNER|CORNERS )

Sets the origin of the sprites drawn with the sprite() function. The default is spriteMode( CENTER ).

mode

either CENTER, RADIUS, CORNER or CORNERS

CENTER x, y specifies the center of the sprite, w, h specifies the sprite's width and height.

RADIUS x, y specifies the center of the sprite, w, h specifies half the sprite's width and height.

CORNER x, y specifies the lower left corner of the sprite, w and h specify the sprite's width and height.

CORNERS x, y sets the lower left coordinate of the sprite's bounding box. w, h sets the upper right coordinate of the sprite's bounding box.

Returns

The current sprite mode if called without arguments. Returns nothing if called with arguments.

spriteSize( name ) top ↑

Syntax

w, h = spriteSize("Planet Cute:Character Boy")
w, h = spriteSize( image )

Returns the pixel size of the sprite specified by name. If the sprite name is valid this function returns two values, width and height.

If the sprite name represents a multi-page PDF, then this function will return three values: width, height, and page count.

name

name of a sprite, in the form "Sprite Pack:Sprite Name"

image

image object

Returns

Width and height of the sprite specified by name, or image object

textMode( MODE ) top ↑

Syntax

textMode()
textMode( CENTER|CORNER )

Sets the origin of text drawn with the text() function. The default is textMode( CENTER ).

mode

either CENTER or CORNER

CENTER: x, y specifies the center of the text.

CORNER: x, y specifies the lower left corner of the text.

Returns

The current text mode if called without arguments. Returns nothing if called with arguments.

lineCapMode( MODE ) top ↑

Syntax

lineCapMode()
lineCapMode( ROUND | SQUARE | PROJECT )

Sets the style of the line caps drawn with the line() function. The default is lineCapMode( ROUND ). Note that lineCapMode() only has an effect if smooth() is set.

mode

either ROUND, SQUARE or PROJECT

ROUND: line ends are rounded with circles

SQUARE: line ends are squared off at the end points

PROJECT: line ends are squared off, but project out as far as if they were rounded

Examples

background(40, 40, 50) smooth() stroke(255) strokeWidth(15) translate(WIDTH/2, HEIGHT/2) lineCapMode(ROUND) line(-30, -30, -30, 30) lineCapMode(SQUARE) line(0, -30, 0, 30) lineCapMode(PROJECT) line(30, -30, 30, 30)

Returns

The current line cap mode if called without arguments. Returns nothing if called with arguments.

fill( red, green, blue, alpha ) top ↑

Syntax

fill()
fill( gray )
fill( gray, alpha )
fill( red, green, blue )
fill( red, green, blue, alpha )
fill( color )

Sets the color used to fill shapes drawn with the ellipse() and rect() functions. Also sets the color of text drawn with the text() function.

gray

int from 0 to 255, specifies value between white and black

alpha

int from 0 to 255, specifies opacity of the fill

red

int from 0 to 255, specifies red amount of the fill

green

int from 0 to 255, specifies green amount of the fill

blue

int from 0 to 255, specifies blue amount of the fill

color

a value of the color datatype

Returns

Four values (r,g,b,a) representing the current fill color if called without arguments. Returns nothing if called with arguments.

noFill() top ↑

Syntax

noFill()

Sets the color of the fill to completely transparent.

tint( red, green, blue, alpha ) top ↑

Syntax

tint()
tint( gray )
tint( gray, alpha )
tint( red, green, blue )
tint( red, green, blue, alpha )
tint( color )

Sets the color used to tint sprites drawn with the sprite() function. This color is multiplied with the sprite's color by default.

Setting a white tint with a partial alpha value will make a sprite semi-transparent.

gray

int from 0 to 255, specifies value between white and black

alpha

int from 0 to 255, specifies opacity of the tint

red

int from 0 to 255, specifies red amount of the tint

green

int from 0 to 255, specifies green amount of the tint

blue

int from 0 to 255, specifies blue amount of the tint

color

a value of the color datatype

Examples

background(127, 127, 127, 255) tint(255, 0, 0) sprite("Planet Cute:Character Boy", WIDTH / 2, HEIGHT / 2)

Returns

Four values (r,g,b,a) representing the current tint color if called without arguments. Returns nothing if called with arguments.

noTint() top ↑

Syntax

noTint()

Sets the color of the tint to white and completely opaque.

stroke( red, green, blue, alpha ) top ↑

Syntax

stroke()
stroke( gray )
stroke( gray, alpha )
stroke( red, green, blue )
stroke( red, green, blue, alpha )
stroke( color )

Sets the color used to outline the shapes drawn with the ellipse() and rect() functions. Also sets the color of lines drawn with the line() function.

gray

int from 0 to 255, specifies value between white and black

alpha

int from 0 to 255, specifies opacity of the stroke

red

int from 0 to 255, specifies red amount of the stroke

green

int from 0 to 255, specifies green amount of the stroke

blue

int from 0 to 255, specifies blue amount of the stroke

color

a value of the color datatype

Returns

Four values (r,g,b,a) representing the current stroke color if called without arguments. Returns nothing if called with arguments.

strokeWidth( width ) top ↑

Syntax

strokeWidth()
strokeWidth( width )

Sets the width of the outline of shapes drawn with the ellipse() and rect() functions. Also sets the width of lines drawn with the line() function.

width

int or float, the width in pixels of the stroke

Returns

The current stroke width if called without arguments. Returns nothing if called with arguments.

noStroke() top ↑

Syntax

noStroke()

Sets the stroke width to zero.

smooth() top ↑

Syntax

smooth()

This enables smooth line drawing. Lines will appear anti-aliased and respect styles set using the lineCapMode() function.

noSmooth() top ↑

Syntax

noSmooth()

This disables smooth line drawing. Lines will appear aliased. Using this option allows you to draw very thin lines clearly.

font( name ) top ↑

Syntax

font()
font( name )

This sets the current font to the font specified by name. If no argument is given font() returns the current font. The default font is "Helvetica".

name

string, the name of the font to use. A list of available fonts can be found by tapping on the font() function in the code editor.

Returns

The current font if called without arguments. Returns nothing if called with arguments.

fontSize( size ) top ↑

Syntax

fontSize()
fontSize( size )

This sets the current font size to the size specified by size. If no argument is given fontSize() returns the current font size. The default font size is 17 points.

size

float, the size of the font (in points). Must be greater than 0.0.

Returns

The current font size if called without arguments. Returns nothing if called with arguments.

fontMetrics() top ↑

Syntax

fontMetrics()

This function returns a table of font metrics for the currently defined font (as defined by font() and fontSize()). The metrics table contains advanced information about the font's measurements, such as ascent, leading, x height, and so on.

Please note that this function only works on iOS 5 and above.

Returns

A table containing the following keys: ascent descent leading xHeight capHeight underlinePosition underlineThickness slantAngle size

textAlign( ALIGN ) top ↑

Syntax

textAlign()
textAlign( LEFT|CENTER|RIGHT )

This sets the alignment of text rendered with the text() function. This is generally used in conjunction with textWrapWidth() to produce multi-line, word-wrapped text aligned to the LEFT, CENTER or RIGHT. If called without arguments this function returns the current text alignment. The default text alignment is textAlign( LEFT ).

ALIGN

Can be LEFT, CENTER or RIGHT

Returns

The current text alignment if called without arguments. Returns nothing if called with arguments.

textWrapWidth( width ) top ↑

Syntax

textWrapWidth()
textWrapWidth( width )

This sets the wrap width, in pixels, of text rendered with text(). If set to a value greater than 0, it causes text to wrap onto the next line when the line's width exceeds the specified width. When this is called without arguments, it returns the current text wrap width. The default text wrap width is 0, which indicates no wrapping, and that text should be rendered on one line.

width

float, width before the text rendered by text() word-wraps

Examples

background(100, 120, 160) font("Georgia") fill(255) fontSize(20) textWrapWidth(70) text("Hello World!", WIDTH/2, HEIGHT/2)

Returns

The current text wrap width if called without arguments. Returns nothing if called with arguments.

Text Metrics

textSize( string ) top ↑

Syntax

width = textSize( string )
width, height = textSize( string )

This function returns the dimensions of the specified string when rendered with the current font size and style. Note that this function returns two values: width and height. You can use these dimensions to, for example, render a button behind a piece of text, position text within a speech bubble, and so on.

string

string, the string to measure

Examples

background(100, 120, 160) font("Georgia") fontSize(20) textWrapWidth(70) -- Get the dimensions of our string w,h = textSize("Hello World!") -- Draw a box behind our text fill(120,0,40) strokeWidth(2) rectMode(CENTER) rect(WIDTH/2,HEIGHT/2,w+15,h+15) fill(255) text("Hello World!",WIDTH/2,HEIGHT/2)

Returns

width and height of the text string when rendered with the current font size and style.

Transform Management

pushMatrix() top ↑

Syntax

pushMatrix()

The pushMatrix() function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling popMatrix(). You can nest calls to pushMatrix() and popMatrix() for more complex object placement.

The following transform calls are preserved when using pushMatrix() and popMatrix(): translate(), rotate(), scale()

popMatrix() top ↑

Syntax

popMatrix()

The popMatrix() function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling popMatrix(). You can nest calls to pushMatrix() and popMatrix() for more complex object placement.

The following transform calls are preserved when using pushMatrix() and popMatrix(): translate(), rotate(), scale()

resetMatrix() top ↑

Syntax

resetMatrix()

This function resets all transformation. It replaces the current transform matrix with the identity matrix. This effectively repositions all drawing at 0, 0, with no rotation and scaling.

Style Management

pushStyle() top ↑

Syntax

pushStyle()

The pushStyle() function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling popStyle(). You can nest calls to pushStyle() and popStyle() in order to provide more control.

Styles set with the following functions are preserved when using pushStyle() and popStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth(), font(), fontSize(), textAlign(), textMode() and textWrapWidth()

popStyle() top ↑

Syntax

popStyle()

The pushStyle() function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling popStyle(). You can nest calls to pushStyle() and popStyle() in order to provide more control.

Styles set with the following functions are preserved when using pushStyle() and popStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()

resetStyle() top ↑

Syntax

resetStyle()

Calling resetStyle() will reset all style parameters to their default values. This will effect whatever style is currently on the top of the stack.

Styles set with the following functions are reset when using resetStyle(): fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()

Images

image top ↑

Syntax

image( width, height )
image.width
image.height
image(data)
image(source)

This type represents a 2D raster image, pixels can be set with image:set(x, y, color) and read with image:get(x, y). Images and sub-rectangles can be copied with image:copy(). Draw images onto the screen using sprite(image,x,y). See the relevant documentation pages for more details.You can access the width or the height of an image through its width and height properties.

The image.premultiplied flag allows you to specify whether the image was created with premultiplied alpha. Generally, for images you create yourself using image:set(), you'll want this set to false (the default). For images used with setContext() you will want this set to true. Note that using an image with setContext() will automatically set its premultiplied flag to true.The constructor can alternatively take png or jpeg encoded binary data which it will decode and use to construct the image. Using this will enable premultiplied alpha, and the encoded data is assumed to be premultiplied.

image(CAMERA) can be used to capture the current frame from the camera into a static image. This is a fairly slow operation and should not be done every frame. If there is no camera frame available (due to the capture source not being available, or still being initialized), an image with width and height of 0 is created.

source

CAMERA constant, to copy the frame from the current capture source

width

integer, the width of the image in pixels

height

integer, the height of the image in pixels

premultiplied

boolean, tells Codea to render this image as a premultiplied image. The default is false.

data

string, a sequence of bytes representing the encoded jpeg or png image data.

Examples

-- Create a 400x400 pixel image myImage = image(400, 400) -- Set a pixel myImage:set(10,10,128,128,128,255) -- Get a pixel r,g,b,a = myImage:get(10,10)
img = image(CAMERA)

Returns

The newly created image of given width and height

image.get( x, y ) top ↑

Syntax

image.get( x, y )

This method returns the red, green, blue and alpha components of the pixel located at x, y in the image.

x

integer, x location of the pixel to query

y

integer, y location of the pixel to query

Examples

r,g,b,a = myImage:get( 15, 15 ) r,g,b = myImage:get( 25, 25 )

Returns

Four values: red, green, blue and alpha representing the color of the pixel at x, y. The values are in the range 0 to 255.

image.set( x, y, color ) top ↑

Syntax

image.set( x, y, color )
image.set( x, y, r, g, b, a)
image.set( x, y, r, g, b)

This method sets the red, green, blue and alpha components of the pixel located at x, y. If no alpha parameter is given, it is assumed to be 255.

x

integer, x location of the pixel to query. 1 is the left most column. Must be less than or equal to the image.width value.

y

integer, y location of the pixel to query. 1 is the bottom row. Must be less than or equal to the image.height value.

color

color object, the color to set the pixel to

r, g, b, a

integer, the red, green, blue and alpha value to set the pixel to. Between 0 and 255.

Examples

myImage:set( 15, 15, color(20,30,40,255) )
myImage:set( 15, 15, 20, 30, 40, 255)

image.copy( x, y, w, h ) top ↑

Syntax

image:copy()
image:copy(x, y, width, height)

This method will copy the pixels in one image into a new image. If no parameters are given, it will copy the whole image, otherwise it will copy the defined subregion. If the region is outside of the image, it will be adjusted to select a valid region from the image. If the rectangle is completely outside of the image, an error will occur.

x

integer, x location of the leftmost pixels of the copy region.

y

integer, y location of the topmost pixels of the copy region

width

positive integer, width in pixels of the copy region

height

positive integer, height in pixels of the copy region

Examples

newImage = myImage:copy()
newImage = myImage:copy(20,40,100,100)

Returns

The newly created image with a copy of the given image or a subregion of it.

Drawing Into Images

setContext( image ) top ↑

Syntax

setContext()
setContext( image )
setContext( image, useDepth )

This call causes all drawing operations to take place on the specified image instead of on-screen. Drawing commands such as ellipse, sprite and rect will render into the image given as an argument to setContext().

Calling setContext() with no arguments causes all drawing operations to return to their regular on-screen drawing functionality. Because Codea uses pre-multiplied drawing, any image passed to setContext() will have its premultiplied flag set to true.

An optional final argument useDepth can be specified to tell setContext to also allocate a depth buffer for the image. By default setContext will not. Allocating a depth buffer impacts performance, but allows rendering of 3D content into an image.

image

image, all drawing operations will occur on this image instead of on screen

useDepth

boolean, whether a depth buffer should be created for this image, defaults to false if not specified

Examples

-- Creates an image of an ellipse and rect function createImage() myImage = image(400,400) setContext( myImage ) ellipse(200, 200, 200) rect(0, 0, 100, 100) setContext() return myImage end

Generators

noise( x, y, z ) top ↑

Syntax

noise( x )
noise( x, y )
noise( x, y, z )

Returns a Perlin noise value in the range -1.0 to 1.0 sampled at location x, y, z. Any parameters not provided to this function are treated as zero.

x

float, x location of the sample

y

float, y location of the sample

z

float, z location of the sample

Returns

Perlin noise value from -1.0 to 1.0 at the given location.

Setting Clipping Bounds

clip( x, y, width, height ) top ↑

Syntax

clip( x, y, width, height )
clip() --Disables clipping

Constrains all drawing performed after this function call to the rectangle specified by x, y, width, height. Any drawing that occurs outside the bounds will not be visible.

This can be used to make split-screen multiplayer games, for example. When called with zero arguments clip() disables the clipping rectangle, allowing drawing to occur anywhere on the screen.

x

integer, x coordinate of the lower-left corner of the clipping rectangle

y

integer, y coordinate of the lower-left corner of the clipping rectangle

width

integer, width of the clipping rectangle

height

integer, height of the clipping rectangle

Constants

WIDTH top ↑

Syntax

WIDTH

This constant is set to the width of the screen in pixels.

Returns

Width of the screen in pixels

HEIGHT top ↑

Syntax

HEIGHT

This constant is set to the height of the screen in pixels.

Returns

Height of the screen in pixels

Variables

ElapsedTime top ↑

Syntax

ElapsedTime

Query this variable to get the current elapsed time, in seconds, while running your project.

Returns

Time in seconds since the start of running the project

DeltaTime top ↑

Syntax

DeltaTime

Query this variable to get the time elapsed, in seconds, since the last draw call while running your project.

Returns

Time in seconds since the start of the previous frame

ContentScaleFactor top ↑

Syntax

ContentScaleFactor

Query this variable to get the content scale factor. This specifies the internal scaling of images and sprites. On retina devices this will be equal to 2, on non-retina devices it will be equal to 1.

Returns

Content scale factor of the viewer

Camera Input

cameraSource( source ) top ↑

Syntax

cameraSource( source )
cameraSource()

Calling cameraSource() will either set the current capture source, or return the currently selected one if called with no parameters.

The capture source determines which input source is used when the CAMERA constant is used in the image() and sprite() functions and as a mesh texture.

CAMERA_BACK is the default capture source.

To get the dimensions of the current capture source frame, use spriteSize(CAMERA)

source

Either CAMERA_FRONT or CAMERA_BACK, determines the source to use.

Examples

cameraSource( CAMERA_FRONT ) cameraSource( CAMERA_BACK ) currentSource = cameraSource()

Returns

CAMERA_FRONT or CAMERA_BACK if called without arguments. Returns nothing if called with arguments.

CAMERA top ↑

Syntax

CAMERA

Uses the current capture source for images, sprites and textures on meshes.

CAMERA is a special constant that can be used with image(), sprite() and mesh.texture. When used with image() it provides an image containing a single snapshot from the device camera. When used with sprite() and mesh.texture it provides a live stream of the device's camera.

Examples

img = image(CAMERA) sprite(CAMERA, x, y) local m = mesh() m.texture = CAMERA

CAMERA_FRONT top ↑

Syntax

CAMERA_FRONT

Select the front camera of the device for use when using CAMERA.

CAMERA_BACK top ↑

Syntax

CAMERA_BACK

Select the back camera of the device for use when using CAMERA.