How to get drawRect() to show on the screen

I'm having a really hard time wrapping my head around the simplest of things in the SDK. I'm trying to follow some beginner videos and cannot get drawRect() to show on the screen. I can get an image to show up fine using the same approach, but the drawRect() and drawLine() functions aren't working for me.

Here's what I have in a file called needle.lua:

local pd <const> = playdate
local gfx <const> = pd.graphics

class('Needle').extends(gfx.sprite)

function Needle:init(x, y, width, height)
    self:moveTo(100, 150)
    self.moveSpeed = 5
    local needleImage = gfx.image.new(width, height)
    gfx.pushContext(needleImage)
        gfx.fillRect(x, y, width, height)
    gfx.popContext()
    self:setImage(needleImage)
end

And here's the main.lua file

import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/crank"

local pd <const> = playdate
local gfx <const> = pd.graphics

import "player"
import "needle"

local function initialize()
    local playerInstance = Player(100, 100, 64, 32)
    playerInstance:add()

    local needleSprite = Needle(100, 150, 200, 1)
    needleSprite:add()
end

initialize()

function playdate.update() 
    gfx.clear()
    gfx.sprite.update()
end

What am I doing wrong here?!

If I’m not mistaken, when you push to context it uses new coordinates. So, on your fillRect, try instead:

gfx.fillRect(0, 0, width, height)

That said , since you’re using subclass OOP stuff anyway, you could also use the Needle’s draw function directly to save a lot of headache:

function Needle:draw()
    gfx.fillRect(0, 0, self.width, self.height)
end

In this case, no need to use an image whatsoever, and just make sure you “setBounds” on your sprite in the init, like:

self:setBounds(0, 0, width, height)
1 Like

Thank you so much! That worked and makes so much more sense than trying to use an image for just drawing a shape.

1 Like