Page 1 of 1

flipping image

Posted: Fri Apr 08, 2011 7:00 pm
by tsturzl
I'm having trouble flipping an image loaded with love.graphics.newImage. I see functions for rotating and scaling but nothing for flipping or transforming an image.

Any help?

Re: flipping image

Posted: Fri Apr 08, 2011 8:06 pm
by thelinx
There's no built-in solution for flipping images.

However, you can use mapPixel for great success.

Code: Select all

function horizontalflip(imagedata)
  local width = imagedata:getWidth()
  imagedata:mapPixel(function (x, y)
    return imagedata:getpixel(width - x, y)
  end)
  return love.graphics.newImage(imagedata)
end
function verticalflip(imagedata)
  local height = imagedata:getHeight()
  imagedata:mapPixel(function (x, y)
    return imagedata:getpixel(x, height - y)
  end)
  return love.graphics.newImage(imagedata)
end
Untested. Should work. Takes an ImageData as an argument. It's probably very slow.
Edit: Actually, doesn't work. Give me some time and I'll have something working.


Here's a flip function I wrote (complete with an example), just for you:

Code: Select all

function flip(dir, imagedata)
	local t, width, height = {}, imagedata:getWidth(), imagedata:getHeight()
	for x = 1, width do
		t[x] = {}
		for y = 1, height do
			if dir == "h" then
				t[x][y] = {imagedata:getPixel(width - x, y - 1)}
			elseif dir == "v" then
				t[x][y] = {imagedata:getPixel(x - 1, height - y)}
			end
		end
	end
	for x = 1, width do
		for y = 1, height do
			imagedata:setPixel(x - 1, y - 1, unpack(t[x][y]))
		end
	end
  return love.graphics.newImage(imagedata)
end

function love.load()
	data = love.image.newImageData("img.png")
	img = love.graphics.newImage(data)
	himg = flip("h", data)
	vimg = flip("v", data)
end

function love.draw()
	love.graphics.draw(img, 5, 5)
	love.graphics.draw(himg, 5, 205)
	love.graphics.draw(vimg, 5, 405)
end
Don't call it too much, as it's not very fast at all. You should only create your flipped images once.

Re: flipping image

Posted: Fri Apr 08, 2011 8:32 pm
by GloryFish
You can supply a negative value to the sx, and sy (scale) parameters of love.graphics.draw() to flip your image on the horizontal and vertical axes, respectively.