graphics.newMask()

Type Function
Library graphics.*
Return value Mask
Revision 2017.3060
Keywords image mask, masking, clipping, bit mask
See also Masking Images (guide)
object:setMask()
object.isHitTestMasked
object.maskScaleX
object.maskScaleY

Overview

Creates a bit mask from an image file. The image is converted internally to grayscale. The white pixels of the bit mask allow the covered image to be visible, while black pixels hide (mask) the covered image. The area outside of the mask must be filled with black pixels which mask off the area outside the mask image.

The function returns a Mask object that can be applied to any display object using object:setMask().

For a walkthrough on how to use image masks, see the Masking Images guide.

Image Mask Requirements

Gotchas

Syntax

graphics.newMask( filename [, baseDir] )
filename (required)

String. The name of the image file to create the mask from.

baseDir (optional)

Constant. Specifies the directory path that contains the mask image. Can be one of the following:

  • system.ResourceDirectory (default)
  • system.DocumentsDirectory
  • system.ApplicationSupportDirectory
  • system.TemporaryDirectory
  • system.CachesDirectory

Examples

Mask on Image
-- Create and position image to be masked
local image = display.newImageRect( "image.png", 768, 1024 )
image:translate( display.contentCenterX, display.contentCenterY )
 
-- Create mask and apply to image
local mask = graphics.newMask( "circlemask.png" )
image:setMask( mask )
 
-- Transform mask
image.maskScaleX, image.maskScaleY = 2,2
Mask on Display Group
local g = display.newGroup()
-- Create and position image to be masked, and insert into group
local image = display.newImageRect( g, "image.png", 768, 1024 )

-- Center the Display Group
g:translate( display.contentCenterX, display.contentCenterY )
 
local mask = graphics.newMask( "circlemask.png" )
g:setMask( mask )
Dynamically-Selected Mask
-- This example shows how to select a different mask image based on the dynamic image suffix
-- It ensures that higher-resolution masks are used when the device resolution warrants it

-- Create and position image to be masked
local image = display.newImageRect( "image.png", 768, 1024 )
image:translate( display.contentCenterX, display.contentCenterY )

-- Create up-value reference for mask
local mask

-- Check the image suffix values and pick the correct mask
if ( display.imageSuffix == "@4x" ) then
    --print( "using @4x" )
    mask = graphics.newMask( "circlemask@4x.png" )
    image:setMask( mask )
    image.maskScaleX = 0.25
    image.maskScaleY = 0.25

elseif ( display.imageSuffix == "@2x" ) then
    --print( "using @2x" )
    mask = graphics.newMask( "circlemask@2x.png" )
    image:setMask( mask )
    image.maskScaleX = 0.5
    image.maskScaleY = 0.5

else
    --print( "using @1x" )
    mask = graphics.newMask( "circlemask.png" )
    image:setMask( mask )
end