Page 1 of 1

rectangles in line mode

Posted: Wed Jul 03, 2019 2:29 pm
by healLV
so basically Ive been having problem with love.graphics.rectangle mode "lines". it seems like they have 1 pixel offset? Im not sure whats happening. below code and image can show what I mean. the code is expected to have both rectangles same size but they are not.
2019-07-03 17_25_11-Untitled.png
2019-07-03 17_25_11-Untitled.png (1.11 KiB) Viewed 4425 times

Code: Select all

function love.load()
	love.window.setMode(640, 480)
	love.graphics.setBackgroundColor(0, 1, 0)
	love.graphics.setLineWidth(1)
	love.graphics.setLineStyle("rough")
end

function love.draw()
	local x, y = 320, 240
	local w, h = 20, 10
	love.graphics.setColor(1, 1, 1, 1)
	love.graphics.rectangle("fill", x, y, w, h)
	love.graphics.setColor(0, 0, 0, 1)
	love.graphics.rectangle("line", x, y - h, w, h)
end

Re: rectangles in line mode

Posted: Wed Jul 03, 2019 8:53 pm
by pgimeno
This is expected. What's happening here is that half of the line extends to one side, and half to the other side, of the given coordinate. But since you're forcing rough line style, LÖVE can't draw "half pixels" (which it normally simulates by reducing the alpha proportionally), and the line's pixels end up at an arbitrary position.

When using "line" mode, the rectangle that you want to draw should actually be drawn 0.5 pixels to the right, and 0.5 pixels down of the position you're currently using. That's where the pixel centre is. It should also be 1 pixel smaller in each dimension, because it will have a 0.5 pixel margin to the left and a 0.5 pixel margin to the right, and similarly for top and bottom. That way, half the line width will extend to one side of the centre of the pixel, and the other half to the other side, and the rectangle will be the right dimension. It will look good even with smooth line style (though LÖVE's smooth line algorithm isn't perfect, so it will "leak" a little bit).

So, for example, if you want to draw a 5x4 pixel rectangle whose outer side extends from 423 to 428 in x and from 298 to 302 in y, with a 1 pixel thick line, like this:
Rectangle-explanation.png
Rectangle-explanation.png (10.46 KiB) Viewed 4399 times
you need to draw it at coordinates (423.5, 298.5) instead of (423, 298), its width should be 427.5 - 423.5 = 4 and its height should be 301.5 - 298.5 = 3. In general, when drawing lines in LÖVE, you need to think in terms of pixel centres.

Re: rectangles in line mode

Posted: Thu Jul 04, 2019 8:17 am
by HDPLocust
Also you can love.graphics.translate(.5, .5) before rendering stuff (except text, it nicely renders with round coords)

Re: rectangles in line mode

Posted: Sat Jul 06, 2019 6:37 am
by healLV
ah I see thanks