Introduction
This article is a bit of a homage to Davidwu's excellent article, A lovely goldfish desktop pet. In that article, David demonstrates using alpha-blending and GDI+ to make a little fish swim across the screen.
I've taken that code and extended it to support multiple fish along with a SysTray icon to control the number of fish in your tank.
I also added some different colored fish images for a little variety.
Using the Code
The code is largely the same as the original, though I've moved things around a bit in order to support multiple fish. Unlike the original code, frames are extracted from the source PNG at startup rather than at each timer tick.
class Frameset : List<Bitmap>, IDisposable
{
public Frameset(Bitmap b, int framecount)
{
if (!Bitmap.IsCanonicalPixelFormat(b.PixelFormat) ||
!Bitmap.IsAlphaPixelFormat(b.PixelFormat))
throw new ApplicationException("The picture must be 32bit
picture with alpha channel.");
FrameWidth = b.Width / framecount;
FrameHeight = b.Height;
for (int i = 0; i < framecount; i++)
{
Bitmap bitmap = new Bitmap(FrameWidth, FrameHeight);
using (Graphics g = Graphics.FromImage(bitmap))
g.DrawImage(b, new Rectangle(0, 0, FrameWidth, FrameHeight),
new Rectangle(FrameWidth * i, 0, FrameWidth, FrameHeight),
GraphicsUnit.Pixel);
Add(bitmap);
}
}
public int FrameWidth { get; private set; }
public int FrameHeight { get; private set; }
public void Dispose()
{
foreach (Bitmap f in this)
f.Dispose();
Clear();
}
}
This greatly reduces the CPU usage for the animation which is important with a whole tankful swimming around. There is also a Form derived from the main FishForm to host the NotifyIcon in the system tray. An instance of this form will always be the first one created. The NotifyIcon context menu allows the user to add and remove fish, show and hide all the fish and of course exit the application.
.NET 4
The project files are all in VS.NET 2010 format, but the only .NET 4 type used is the Tuple. Sacha posted a version of a Tuple in the comments below. So if you want to play with this in 2008 and .NET 3.5, you'll need to incorporate that snippet or otherwise replace the Tuple usage, which shouldn't be too hard.
Conclusion
Oh, and I kind of cheated on the fish colorizing. I color shifted the source PNG in Paint.Net and saved each one as a new set of images. That's why the project size is large. Perhaps someday I'll correct that short cut but for now my apologies for the extra large download. :)
That's about all there is to it. It's been a fun little project to play around with (and the family and friends I've given it to have enjoyed it as well). This will probably be my last WinForms article. I've caught the WPF bug and am finally cresting the learning curve.
History