Manipulating an image dynamically
This recipe will demonstrate using the imaging SDK to resize and crop an image, and then saving that image to the gallery.
Getting ready
This recipe builds on the example created in the prior two recipes. The complete source code is available in Ch01_Example4
.
How to do it...
In the Initialize()
method, change the code as follows:
Image image = new Image(ImageMode.Rgba,new ImageSize(500,300),new ImageColor(0,0,0,0)); Image resizedImage, croppedImage; image.DrawText("Hello World", new ImageColor(255,255,255,255), new Font(FontAlias.System,96,FontStyle.Italic), new ImagePosition(0,150)); croppedImage = image.Crop (new ImageRect(0,0,250,300)); resizedImage = croppedImage.Resize(new ImageSize(500,300)); _texture = new Texture2D(resizedImage.Size.Width,resizedImage.Size.Height,false,PixelFormat.Rgba); _texture.SetPixels(0,resizedImage.ToBuffer()); resizedImage.Export("My Images","HalfOfHelloWorld.png"); image.Dispose(); resizedImage.Dispose(); croppedImage.Dispose();
How it works...
First, we dynamically generate our image just like we did in the previous recipe. We then crop that image to half its width, by calling the Crop()
function and providing an ImageRect
variable half the size of the image. Crop returns a new image (it is not destructive to the source image) that we store in croppedImage
. We then resize that image back to the original size by calling the Resize()
function on croppedImage
, with the original size specified as an ImageSize
object. Like Crop()
, Resize()
is not destructive and returns a new image that we store in resizedImage
. We then copy the pixels from resizedImage
into our texture using SetPixels()
.
Next, we call Export()
, which saves our cropped and resized image in a folder called My Images
as a file named HalfOfHelloWorld.png
on your device. Finally, we call Dispose()
on all three images, to free up the memory they consumed.
Now if you run your code, instead of "Hello World", you simply get "Hello".
There's more...
When run on the simulator, export
will save the image to your My Pictures
folder. Be sure to call Dispose()
, or wrap within a using
statement all objects that implement IDisposable
, or you will quickly run out of memory. Most resources like images and textures require disposal.