1. Merging a transparent image on another
- Posted by Ricardo Niederberger Cabral <rnc at BIGFOOT.COM>
Jan 23, 1998
-
Last edited Jan 24, 1998
I would like to know the best method for merging a transparent image with
another image.
Is the following function the best way to do this ?
----------
function SpriteMerge(sequence foreg,sequence backg,sequence pos)
-- "display" foreg on backg at position pos, respecting foreg's
transparency
sequence merged
merged=backg
for y=1 to length(foreg) do
for x=1 to length(foreg[1]) do
if foreg[y][x] then merged[y+pos[2]-1][x+pos[1]-1]=foreg[y][x]
end if
end for
end for
return merged
end function
----------------
---
Ricardo Niederberger Cabral
<rnc at bigfoot.com>
http://www.infolink.com.br/~rnc/
2. Re: Merging a transparent image on another
At 23:11 23/01/98 -0200, Ricardo Niederberger Cabral wrote:
>I would like to know the best method for merging a transparent image with
>another image.
>Is the following function the best way to do this ?
>----------
>function SpriteMerge(sequence foreg,sequence backg,sequence pos)
> -- "display" foreg on backg at position pos, respecting foreg's
>transparency
> sequence merged
> merged=backg
> for y=1 to length(foreg) do
> for x=1 to length(foreg[1]) do
> if foreg[y][x] then merged[y+pos[2]-1][x+pos[1]-1]=foreg[y][x]
>end if
> end for
> end for
> return merged
>end function
>----------------
Try this
constant sprite_width =?
sprite_height=?
function sprite_merge(sequence foreg,sequence backg, sequence pos)
sequence mask,piece
--***--
piece={bakg[pos[2]][pos[1]..pos[1]+sprite_width-1]}
for y=1 to sprite_height-1
piece=append(piece,backg[pos[2]+y][pos[1]..pos[1]+sprite_width-1])
end for
--***--
mask=(foreg=0)
piece=piece*mask+foreg
display_image({0,0},backg)
display_image(pos,piece)
return piece
end function
display_image({0,0},backg)
display_image(pos,piece)
I havn't tested it but it should work.
If the background image is already on the screen,
the bit of code between the two "--***--" comments
can be replaced by:
If you are using lots of sprites you will want to pre-
generate masks for your sprites to save time.
This method generates a 2D sequence(mask) where each elemant is
equal to 1 if the corresponding element in the sprite is 0, and 0
if the corresponding element in the sprite is non-zero.
multiplying this mask with an equal sized section cut out of the
background causes the background to be multiplied by zero where
the sprite is non-zero. This 'cuts out' a shadow of the sprite.
The sprite sequence can then be pasted on top with simple addition.
All of this happens on these two lines
mask=(foreg=0)
piece=piece*mask+foreg
Check out the "operations on sequences" section of refman.doc
for more info.
Graeme