Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the GIF Animation effect of iOS

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article is about iOS GIF animation effect to share with you how to achieve, the editor feels very practical, so share with you to learn, I hope you can learn something after reading this article, do not say much, follow the editor to have a look.

The usage scenario of GIF in iOS

The usage scenario of GIF in iOS has the following three aspects.

(1) the GIF picture is decomposed into a single frame.

(2) A series of single-frame pictures are synthesized into GIF pictures.

(3) GIF animation effect is displayed on iOS system.

In the aspect of GIF synthesis and decomposition, we will come into contact with ImageIO, the core framework of iOS image processing. As the core framework of image processing in iOS system, it provides us with a variety of rich API. The GIF decomposition and synthesis functions to be realized in this paper can be easily realized through ImageIO. GIF animation display effect will be combined with UIImageView and timer, using frame-by-frame display to present GIF animation effects for everyone.

GIF decomposition of single frame picture 1 GIF picture decomposition process

The process of decomposing GIF into a single frame is as follows.

The whole process is divided into 5 modules and 4 processes, which are as follows.

(1) read GIF pictures locally and convert them to NSdata data types.

(2) NSData is used as the input of ImageIO module.

(3) get the output data of ImageIO: UIImage.

(4) store the acquired UIImage data locally in JPG or PNG format.

In the whole process of GIF image decomposition, ImageIO is the core part of the process. It is responsible for parsing the GIF file format and converting the parsed data into a frame of picture output. Fortunately, we are not the creators of the wheel, but we just need to use the wheel. So in this book, instead of studying the specific implementation of the GIF decomposition and synthesis algorithm, we focus on how to use the ImageIO framework to achieve the required functions.

2 implementation of GIF image decomposition code

Before formally analyzing the code, let's take a look at the file structure of the entire project, as shown in the figure.

The source file uses a plane.gif file. The viewDidLoad () method in the ViewController.swift file contains all the code that breaks the GIF picture into a single frame and saves it locally. The following is combined with "the process of decomposing GIF into a single picture" to achieve this function.

Function module 1: read the GIF file and convert it to NSdata type.

1 let gifPath:NSString = Bundle.main.path (forResource: "plane", ofType: "gif")! As NSString 2 let gifData:Data = try! Data (contentsOf: URL (fileURLWithPath: gifPath as String))

Line 1 of the code uses the path method to get the file address with the file name plane and the file format gif. Line 2 takes the file information and loads it into the gifData (NSData type) variable. So far, the first part of the whole process has been completed.

Function module 2: use ImageIO framework to traverse all GIF subframes. It is important to note that using ImageIO, you must convert the read NSdata data to a data type that ImageIO can handle, which is implemented using CGImageSourceRef. The processing flow of the corresponding function module is as follows.

1 let gifDataSource:CGImageSource = CGImageSourceCreateWithData (gifData as CFData, nil)! 2 let gifImageCount:Int = CGImageSourceGetCount (gifDataSource) 3 for i in 0...gifImageCount-1 {let imageref:CGImage? = CGImageSourceCreateImageAtIndex (gifDataSource, I, nil) let image:UIImage = UIImage (cgImage: imagerefefull scaleGroupe UIScreen.main.scaleMageOrientation.up)}

The following is a description of the functions of ImageIO in the GIF data processing process. Line 1 of the code converts the GIF raw data type NSdata to a data type CGImageSourceRef that ImageIO can handle directly. Line 2 gets the number of frames of the current GIF image. We know that GIF images are made up of frames, so this line is to get the number of pictures that make up GIF images. Line 3 traverses the CGImageSource data according to the sequence number of the picture, and converts the traversal result to UIImage using the UIImage system method.

Here we focus on introducing two methods.

The CGImageSourceCreateImageAtIndex method returns CGImage type data for one of the frames in the GIF. The method has three parameters, parameter 1 is the GIF raw data, parameter 2 is the sequence number in the GIF subframe (the sequence number starts from 0), and parameter 3 is some selection parameters for GIF data extraction, so it is set to nil because it is not very commonly used here.

Public func CGImageSourceCreateImageAtIndex (_ isrc: CGImageSource, _ index: Int, _ options: CFDictionary?)-> CGImage?

The following is the method of the UIImage class, which is used to instantiate the UIImage instance object. The method has three parameters, parameter 1 is the content that needs to build UIImage, note that the content here is the type of CGImage, parameter 2 is the conversion coefficient between the physical pixel of the mobile phone and the display resolution of the mobile phone and the mobile phone, and parameter 3 indicates the image direction of the constructed UIImage. Through this method, you can build an image with a specified direction at a certain mobile phone resolution, and of course the image type is UIImage.

Public init (CGImage cgImage: CGImage, scale: CGFloat, orientation: UIImageOrientation)

UIImage has been obtained through the above two steps, but UIImage is not the image format we usually see, the biggest feature of this image format is that it cannot be stored as a local picture format, so if you need to save the image locally, you need to convert the UIImage data type to PNG or JPG type image data before you can store the image locally.

Here is the complete GIF image decomposition and saving code:

Override func viewDidLoad () {1 super.viewDidLoad () 2 let gifPath:NSString = Bundle.main.path (forResource: "plane", ofType: "gif")! As NSString 3 let gifData:Data = try! Data (contentsOf:URL (fileURLWithPath: gifPath as String)) 4 let gifDataSource:CGImageSource = CGImageSourceCreateWithData (gifData as CFData, nil)! 5 let gifImageCount:Int = CGImageSourceGetCount (gifDataSource) 6 for i in 0...gifImageCount-1 {7 let imageref:CGImage? = CGImageSourceCreateImageAtIndex (gifDataSource, I, nil) 8 let image:UIImage = UIImage (cgImage: imagerefeflow scaleGlug UIScreen.main.scaleMageOrientation.up) 9 let imageData:Data = UIImagePNGRepresentation (image)! 10 var docs=NSSearchPathForDirectoriesInDomains (.documentDirectory, .userDomainMask True) 11 let documentsDirectory = docs [0] as String 12 let imagePath = documentsDirectory+ "/\ (I)" + ".png" 13 try? ImageData .write (to: URL (fileURLWithPath:imagePath), options: [.atomic]) 14 print ("\ (imagePath)")}}

Line 1 of the code uses the UIImagePNGRepresentation method to store the UIImage data type as the data data type in PNG format, line 2 and line 3 get the application's Document directory, and line 4 calls the write method to write the picture to the local file. If you want to see the effect of the final write, you can add print information on the last line, print out the file writing path, and see if the image is written successfully.

3. The final effect of GIF image decomposition

You can get the path where the picture was finally saved through the last line of print ("(imagePath)") in the above code. Enter the path to see the final decomposition result of the image shown below.

According to the picture above and below, under the Mac system, use the viewing tool of the system picture to view the framing result of the GIF picture. Compared with the content in the picture, we can see that the result of GIF picture decomposition is correct.

Sequence image synthesis GIF image 1 GIF picture synthesis idea

The process of multi-frame image synthesis GIF and the process of GIF decomposing multi-frame images are reciprocal, and the process of GIF image decomposition is reversed, which is the process of GIF image synthesis. Here, the 67 sequence single-frame images decomposed above are described as the input sources that need to be processed.

Functionally, the composition of GIF images is divided into the following three main parts.

(1) load 67 pieces of original data sources to be processed.

(2) build the GIF file in the Document directory.

(3) set the attribute of GIF file and use ImageIO to encode GIF file.

Implementation of 2 GIF picture composition code

The following code is written based on the three main steps of the GIF build. The function of the first part of the code is to read 67 PNG pictures into the NSMutableArray array. Line 1 initializes the variable array, line 2 traverses 67 local pictures, line 3 builds 67 picture names according to the naming rule of the picture, and line 4 loads the local picture. The last line loads the read pictures into the images variable array in turn.

/ / Part1: read 67 png pictures 1 let images:NSMutableArray = NSMutableArray () 2 for i in 0.. 66 {/ / traverse 67 local pictures 3 let imagePath = "\ (I) .png" / / build picture name 4 let image:UIImage = UIImage (named: imagePath)! / / 5 images.addObject (image) / / add pictures to the array}

The function of the second part of the code is to build the GIF file path in the Document directory. The specific implementation is shown below.

/ / Part2: create a gif file in the Document directory 1 var docs=NSSearchPathForDirectoriesInDomains (.documentDirectory, .userDomainMask, true) 2 let documentsDirectory = docs [0] as String 3 let gifPath = documentsDirectory+ "/ plane.gif" 4 print ("\ (gifPath)") 5 let url = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, gifPath as CFStringmom CFURLPathStyle.cfurlposixPathStyle, false) 6 let destion = CGImageDestinationCreateWithURL (URL, kUTTypeGIF, images.count, nil)

Line 1 and line 2 of the code get the Document path address, and the third line of code forms the complete plane.gif file path under the Document path when the string is concatenated. To make it easy to see the path to the GIF file, line 4 prints out the path to the GIF file. Line 5 converts the plane.gif file path from string type to URL type. The last line of code is a very important method for building GIF images in ImageIO, and we focus on analyzing the function and function of this method.

Public func CGImageDestinationCreateWithURL (_ url: CFURL, _ type: CFString, _ count: Int, _ options: CFDictionary?)-> CGImageDestination?

The function of the CGImageDestinationCreateWithURL method is to create a target object of a picture. In order to make it easier for everyone to understand, the target object of the picture is compared to a collection.

CGImageDestination structure

A series of parameters that make up the target object of the current picture are described in the collection, such as the URL address of the picture, the picture type, the number of picture frames, configuration parameters and so on. In this code, the local file path of plane.gif is passed to the picture target object as parameter 1, parameter 2 describes the type of picture as GIF picture, parameter 3 indicates the number of frames composed of the current GIF picture, parameter 4 temporarily gives it a null value.

So far, the image source to be processed has been loaded into the code, and the GIF image Destination has been built. Now you need to use the ImageIO framework to encode multiple PNG images into GIF images. The processing flow is as follows.

The specific implementation code is as follows:

/ / Part3: set the properties of gif images and use 67 png images to construct gif 1 let cgimagePropertiesDic = [kCGImagePropertyGIFDelayTime as String:0.1] / / set the playback time between frames 2 let cgimagePropertiesDestDic = [kCGImagePropertyGIFDictionary as String:cgimagePropertiesDic]; 3 for cgimage in images {4 CGImageDestinationAddImage (destionimages, (cgimage as AnyObject) .cgImage!, cgimagePropertiesDestDic as CFDictionary?) } / / add each frame element 5 let gifPropertiesDic:NSMutableDictionary = NSMutableDictionary () 6 gifPropertiesDic.setValue (kCGImagePropertyColorModelRGB,forKey: kCGImagePropertyColorModel as String) 7 gifPropertiesDic.setValue (16, forKey:kCGImagePropertyDepth as String) / / set the color depth of the image 8 gifPropertiesDic.setValue (1, forKey:kCGImagePropertyGIFLoopCount as String) / / set the number of Gif execution times 9 let gifDictionaryDestDic = [kCGImagePropertyGIFDictionary as String:gifPropertiesDic] 10 CGImageDestinationSetProperties for the gif image object; / / set the attribute 11 CGImageDestinationFinalize (destion!) for the gif image

Line 1 of the code sets the GIF picture property and sets the display interval of each picture in the current GIF to 0.1s. Line 2 of the code builds an GIF picture attribute dictionary, which is initialized with the time interval between frames of GIF. Line 4 of the code uses the traversal method to quickly append the prepared image to the Destination of the GIF image. Line 5 of the code initializes a mutable dictionary object, which is mainly used to set the properties of each picture in the GIF picture. Line 6 sets the color space format of the picture to RGB (Red Green Blue tricolor) type. Line 7 sets the color depth of the image. Generally speaking, a black-and-white image is also known as a binary image, with a color depth of 1, indicating the first square of 2, that is, two colors: black and white. Grayscale images generally have a color depth of 8, representing the power of 2 to the power of 8, with a total of 256 colors, that is, there are 256 gradual changes from black to white. For color pictures, there are generally 16-bit depth and 32-bit depth, which is set to 16-bit depth color pictures. Line 8 of the code sets the number of times the GIF image is executed, which is set here to execute once. Lines 9 and 10 of the code are responsible for adding the various properties set by the image above to the Destination target of GIF. The last line finishes building the Destination object file for GIF.

You can print out the path of the current GIF image, where you can see the resulting GIF image.

Gif image display

IOS native does not support the direct display of GIF images, from the previous analysis, GIF images are composed of a single frame of pictures, so as long as the decomposition of GIF images, the next is the problem of multi-group image display. I would like to introduce you to another form of picture presentation, that is, the display of GIF multi-frame pictures based on UIImageView.

Through the analysis of the idea of GIF picture display, we can know that showing GIF under iOS is divided into two steps: the first step is to decompose the GIF picture into a single picture, and the second step is to show multi-frame pictures under iOS. UIImageView is a UI component for displaying pictures, but it also has some animation properties that can be used for frame-by-frame animation.

Considering that the GIF image has been decomposed in the first step, the 67 images after decomposition are loaded here first.

The specific implementation code of UIImageView multi-frame image display is as follows.

1 var images: [UIImage] = [] 2 for i in 0.66 {/ / traverse 67 local images 3 let imagePath = "\ (I) .png" / / build image name 4 let image:UIImage = UIImage (named: imagePath)! 5 images.append (image) / / add pictures to the array} 6 let imageView = UIImageView () 7 imageView.frame = self.view.bounds 8 imageView.contentMode = UIViewContentMode.Center 9 self.view. AddSubview (imageView) 10 imageView.animationImages = images 11 imageView.animationDuration = 5 12 imageView.animationRepeatCount = 1 13 imageView.startAnimating ()

Line 1 of the code initializes an array object with child elements of type UIImage. Lines 2 through 5 load 67 images into the current array in turn through the for loop. Line 6 instantiates a UIImageView instance object. Lines 7 and 8 set the frame position property of the UIImageView instance object and how the picture is stretched, which is set to be centered. Line 9 adds UIImageView to the self.view layer. Line 10 adds the 67 images initialized to the animationImages of the UIImageView instance, which is equivalent to setting the contents of UIImageView. Line 11 sets the UIImageView picture animation playback cycle. Line 12 sets the number of animation repeats. The last line starts the UIImageView multi-frame picture display animation.

The above is how the GIF animation effect of iOS is realized, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report