Practical development tips for Windows Phone (40): Use NGif to create GIF images

Source: Internet
Author: User

NGif is a class library used in. net to create GIF images. It can be migrated to windows phone and created in windows phone.

GIF animation displays images in sequence within a certain period of time and saves multiple images as an image file to form an animation.

There are two different ways to migrate NGif to windows phone.

1. In the original NGif, the image object is used to represent the image of the current frame. In windows phone, the image object is also available. You only need to modify some incompatible code.

2. Use WriteableBitmap to represent the image of the current frame.

In the demo at the end of the text, both methods are provided by source code.

Method 1:

In NGif, using the GDI technology, we can use the WriteableBitmap extension method to replace it.

Image temp =    new Bitmap(width, height);Graphics g = Graphics.FromImage(temp);g.DrawImage(image, 0, 0);image = temp;g.Dispose();

Can be written

WriteableBitmap temp = new WriteableBitmap(image,null);temp.Resize(width, height, WriteableBitmapExtensions.Interpolation.NearestNeighbor);image = new Image { Source = temp };

You can view other migration code in the source code.

This article will use the migrated NGif to select an image from the album, create a GIF image, and finally display the picture in the program. The homepage runs as follows:

The template selected for the image is as follows:

        <DataTemplate x:Key="DT_Image">            <Grid>                <Button Click="Button_Click">                    <Button.Template>                        <ControlTemplate>                            <Image Source="{Binding Thumbnail}" Height="100" Width="100" Margin="5" />                        </ControlTemplate>                    </Button.Template>                </Button>                <Image Source="selected.png"                        Height="32" Width="32"                        Visibility="{Binding IsSelectedVisibility}"                        HorizontalAlignment="Right"                        VerticalAlignment="Bottom"/>            </Grid>                    </DataTemplate>

 

The ListBox code is as follows:

            <ListBox x:Name="lbDefault" Margin="7,-10,0,0"                      ItemTemplate="{StaticResource DT_Image}"                      ItemsSource="{Binding DefaultImages}">                <ListBox.ItemsPanel>                    <ItemsPanelTemplate>                        <toolkit:WrapPanel/>                    </ItemsPanelTemplate>                </ListBox.ItemsPanel>            </ListBox>

 

You can view the program source code by loading images from the album.

Let's take a look at the GIF production code.

Private void btn2_Click (object sender, RoutedEventArgs e) {List <PhotoCell> list = new List <PhotoCell> (); foreach (var item in defaultImages) {if (item. isSelectedVisibility = System. windows. visibility. visible) {list. add (item) ;}} if (list. count = 0) {MessageBox. show ("select image"); return;} String outputFilePath = "test2.gif"; GifLib2.AnimatedGifEncoder maker = new GifLib2.AnimatedGifEncoder (); mak Er. start (outputFilePath); maker. setdelay( 500); //-1: no repeat, 0: always repeat maker. setRepeat (0); foreach (var item in list) {maker. addFrame (item. image. resize( 320,320, WriteableBitmapExtensions. interpolation. nearestNeighbor);} maker. finish (); MessageBox. show ("done, find it in iso named:" + outputFilePath); NavigationService. navigate (new Uri ("/DisplayGifPage. xaml? Name = "+ outputFilePath, UriKind. Relative ));}

 

First, instantiate the AnimatedGifEncoder object, set its output path, interval, and number of repetitions, and then add the image to its frame.

After creating a Gif, We will display the Gif in the program. At this time, we will use GifDecoder to decode the Gif into one image.

Private void LoadGif (string name) {GifDecoder decoder = new GifDecoder (); using (var store = IsolatedStorageFile. GetUserStoreForApplication () {if (! Store. fileExists (name) {MessageBox. show ("gif image does not exist"); return;} using (var stream = store. openFile (name, System. IO. fileMode. open, System. IO. fileAccess. read) {decoder. read (stream); // get frame size to set image size Size size = decoder. getFrameSize (); image. width = size. width; image. height = size. height; int delay = decoder. getDelay (1); // 0 stand for loop forever, otherwise is the real count int loopCount = decoder. getLoopCount (); // decoder. getLoopCount int imagecount = decoder. getFrameCount (); for (int I = 0; I <imagecount; I ++) {imageList. add (decoder. getFrame (I) ;}displaygif (delay, loopCount );}}}

Load a Gif from an independent bucket and obtain its attributes: number of repetitions, number of frames, and the image corresponding to each frame. Then, use a Timer to display the Gif:

Private void DisplayGif (int delay, int loopCount) {DispatcherTimer timer = new DispatcherTimer (); timer. interval = TimeSpan. fromMilliseconds (delay); int index = 0; int loopedCount = 0; // number of cycles timer. tick + = (sender, e) =>{// if it is a permanent loop if (loopCount = 0) {if (index = imageList. count-1) {index = 0 ;}} else {if (loopCount = loopedCount) {timer. stop () ;}loopedcount ++;} image. source = imageList [index]; index ++;}; timer. start ();}

This article only describes how to make a Gif in windows phone and decode and display it. Many of the code can be optimized. You can use the code in this example as appropriate.

The source code can be found here.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.