I posted a sample texture processor that shows how to resize a texture in the content pipeline. Creating this highlighted a small issue with BitmapContent objects that I wanted to mention.
To create a resized copy of a BitmapContent is pretty easy, you just have to copy the source bitmap to a destination bitmap that is a different size.
BitmapContent.Copy(sourceBM, destinationBM);
The awkward bit is creating a destination bitmap that is the same type as the source bitmap. BitmapContent is an abstract class and the common concrete implementation of BitmapContent is the generic class PixelBitmapContent<T>. And that's where the problem lies, we need to create an instance of a generic class when the type of T is not known until run time. I could only think of two ways to do this; one, use a switch statement to handle all the different types that T in PixelBitmapContent<T> will usually be (Color, Vector4, HalfVector4, etc.); or two, use the Activator class to create an instance of a given type. The second option is shorter so that's my favourite.
private static BitmapContent CreateBitmap(Type bitmapType, int width, int height)
{
return (BitmapContent)Activator.CreateInstance(
bitmapType,
new object[] { width, height });
}
The above method will create a bitmap of the type passed in. If the type isn't derived from BitmapContent, then this method will fail with an exception, so it should really have a try/catch block to deal with that. I don't mind using the Activator, this situation is perfect for it but it might be better if this method was available as BitmapContent.CreateBitmap() or similar so that it's a little more obvious for people who don't know about the Activator class.
While writing the sample I had a need to deal with power of two numbers (that is the sequence of numbers given by 2^n). Computers like power of two numbers for all sorts of reasons and graphics cards are no exception - most graphics cards prefer textures to be power of two sizes (256x256, 128x512, etc.), especially textures with mipmaps. Here are a couple of methods that use bit twiddling magic (hey, it's magic to me) for dealing with power of two numbers.
private static bool IsPowerOfTwo(int n)
{
return ((n & (n - 1)) == 0);
}
private static int RoundUpPowerOf2(int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
I can take no credit for them, I found them on this very useful page but I wanted to post them here for future use and just as a reminder that all that C/C++ style bit twiddling can still apply when working with C#.
Posted
Wed, Aug 15 2007 4:52 PM
by
leaf