flipping image

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
tsturzl
Party member
Posts: 161
Joined: Fri Apr 08, 2011 3:24 am

flipping image

Post 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?
User avatar
thelinx
The Strongest
Posts: 857
Joined: Fri Sep 26, 2008 3:56 pm
Location: Sweden

Re: flipping image

Post 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.
GloryFish
Prole
Posts: 19
Joined: Tue Jan 11, 2011 4:43 pm

Re: flipping image

Post 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.
Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests