I want to put a texture on the rectangle so that it doesn't stretch

I want to put a texture on the rectangle so that it doesn’t stretch. At the moment, it stretches along the edges of the rectangle. This does not happen when superimposed on a circle. Help me, how do I do this?


        local projectIcon = display.newRoundedRect(_cx, y, _dw / 10, _dh / 10, 10)
        projectIcon.fill = { type="image", filename="res/data/images/defaultIcon.png" }

The reason it doesn’t happen with a circle is that a circle has equal dimensions in both width and height, so the texture doesn’t get stretched. In a rectangle, the width and height are different, so the texture gets stretched to cover the whole area unless you adjust the scaling.

Maybe you should do something like this:


local projectIcon = display.newRoundedRect(_cx, y, _dw / 10, _dh / 10, 10)
projectIcon.fill = { type="image", filename="res/data/images/defaultIcon.png" }

local ratio = (_dw / 10) / (_dh / 10) -- Aspect ratio of projectIcon
local imageRatio = 1 -- Assuming your image is square (adjust if it's not)

if ratio > imageRatio then
    projectIcon.fill.scaleY = ratio
else
    projectIcon.fill.scaleX = 1 / ratio
end
1 Like

The problem is that the image can be absolutely anything, any size at all, I need an automatic way…

Implement something like this:

local projectIcon = display.newRoundedRect(_cx, y, _dw / 10, _dh / 10, 10)
projectIcon.fill = { type="image", filename="res/data/images/defaultIcon.png" }

local ratio = (_dw / 10) / (_dh / 10) -- Aspect ratio of projectIcon

local refImg = display.newImage( "res/data/images/defaultIcon.png" )
local imageRatio = refImg.width / refImg.height

display.remove(refImg)
refImg = nil

if ratio > imageRatio then
    projectIcon.fill.scaleY = ratio
else
    projectIcon.fill.scaleX = 1 / ratio
end