Hi all,

is there any convenient way to build CSS sprites, or refactor images to CSS 
sprites, in Wicket yet? If not, I'd be happy to contribute a set of class I've 
written for that purpose.

(In case I've overlooked a feature for this in Wicket, please just stop reading 
and tell me ;))

The code I've written is intended as a drop-in replacement for the Image 
component (it's actually a subclass of Image), but if you like it, it might 
make sense to incorporate the functionality into Image itself. It also depends 
on a central sprite registry that keeps track of the images that are available 
as sprites in a sprite "atlas" (a super-image that contains several sprites). 

Technically, the code uses a SpriteRegistry in the (Web)Application. 
Application code registers sprites in init() like this:

getSpriteRegistry().register(false,
  new PackageResourceReference(MyAnchor.class, "image1.png"),
  new PackageResourceReference(MyAnchor.class, "image2.png"),
  new PackageResourceReference(OtherAnchor.class, "something.png"));

(* see below for the meaning of the first parameter). Doing this causes a 
super-image containing all specified images to be rendered at startup. The 
contained images may use any format supported by ImageIO, but the atlas format 
is currently restricted to PNG (but it wouldn't be hard to support a format 
parameter). There's also currently no logic to find an optimized layout of the 
sprites in the atlas -- they're simply placed in a long horizontal strip, 
left-to-right, possibly with lots of wasted space below. A pluggable layout 
strategy might be useful in the future.

Then, pages/components are expected to use the class SpriteImage instead of 
Image (as said above, it's a subclass). SpriteImage supports IMG, SPAN and DIV 
elements and will do all the magic: Convert IMG to SPAN, add "display: 
inline-block" to IMG/SPAN, and add background-image, background-position, width 
and height.

SpriteImage will actually first resolve its image, then look if it can be found 
in the application's SpriteRegistry. If not, it just falls back to its normal 
logic (supporting DIV and SPAN, though). This means you can basically use 
SpriteImage everywhere. Currently it will turn an IMG to a SPAN with 
background-image though, but we might check for that and leave a non-sprite IMG 
alone.

* the first parameter tells register() whether missing image resources are OK. 
If an image resource is missing, "not ok" throws an exception, while "ok" will 
cause the sprite to be a 0x0 image. This was very convenient in my case, but I 
could see why this isn't very clean for the general case. It'S not essential 
for me.

Please tell me if you are interested in getting this into Wicket core. No files 
attached because I didn't want to clutter the mailing list ;)

Greetings,
Martin Geisse

Reply via email to