官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 松原市| 邮箱| 连云港市| 根河市| 炉霍县| 江川县| 隆昌县| 灵台县| 山阴县| 汪清县| 清丰县| 兴安县| 嘉兴市| 广宗县| 新化县| 红安县| 四子王旗| 手游| 清苑县| 自治县| 化德县| 舞钢市| 精河县| 龙泉市| 姜堰市| 柞水县| 赤水市| 屏东市| 佛坪县| 安平县| 兴城市| 长岭县| 酒泉市| 资阳市| 鹤岗市| 那坡县| 高州市| 栾城县| 柳州市| 沭阳县| 磐安县|