Using `DrawFaded` with Sprite class?

I have a UI menu item (implemented as an extension of the Sprite class) that I'd like to grey out to signal to the user that they cannot interact with it. I found the drawFaded effect which appears to be right for the job. The way that I tried to implement was:

class('MenuItem').extends(gfx.sprite)
-- Initialize the UI menu item as an extension of the Sprite class
function MenuItem:init(x, y, image_path)
    MenuItem.super.init(self)
    self:moveTo(x, y)
    local image = gfx.image.new(image_path)
    self:setImage(image)
    self:add()
end

-- When applicable the game calls `fadeout` in order to fade the UI item
function MenuItem:fadeout()
    local dither_type = self:getImage().kDitherTypeDiagonalLine
    -- Also tried: local dither_type = gfx.image.kDitherTypeDiagonalLine
    local faded_image = self:getImage():drawFaded(0, 0, 0.5, dither_type)
    self:setImage(faded_image)
end

When I try to run this I don't get an error, but the UI image disappears entirely. I tried playing around with some of the arguments in the drawFaded function without success. Help is appreciated, thanks!!

Running on Linux (Ubuntu 22.04)

The issue is that drawFaded does not actually return a new image, it only draws it to the screen. So in order to use the faded image in a sprite you could just save the two different versions of the image as a part of your menuitem object and switch between them like this:

class('MenuItem').extends(gfx.sprite)
-- Initialize the UI menu item as an extension of the Sprite class
function MenuItem:init(x, y, image_path)
    MenuItem.super.init(self)

	self.normal_image = gfx.image.new(image_path)

	local width, height = self.normal_image:getSize()
	self.faded_image = gfx.image.new(width, height, gfx.kColorClear)
	
	gfx.pushContext(self.faded_image)
    self.normal_image:drawFaded(0, 0, 0.5, gfx.image.kDitherTypeDiagonalLine)
	gfx.popContext()

    self:moveTo(x, y)
    self:setImage(self.normal_image)
    self:add()
end

function MenuItem:fadeout()
    self:setImage(self.faded_image)
end

function MenuItem:fadein()
    self:setImage(self.normal_image)
end
2 Likes

self.faded_image = self.normal_image:fadedImage(0.5, gfx.image.kDitherTypeDiagonalLine)

should work, also. :wink:

3 Likes

I didn't realize there was a separate function that actually does return a new image. That's definitely a more straightforward way to do it lol.

That follows a common pattern, fyi:

  • drawRotated() / rotatedImage()
  • drawScaled() / scaledImage()
  • drawWithTransform() / transformedImage()
  • drawBlurred() / blurredImage()

I'll move fadedImage() up below drawFaded() (ditto for blurred) to make those more obvious.

1 Like

Another reason I didn't realize is I mostly work in C, where the fade and blur methods don't seem to be available. Is there any way they could be added to the C API?

1 Like

Wow, I completely missed that. :man_facepalming: I've filed that, will get around to it.. soon I hope.

2 Likes