Ios--core Animation Knowledge Excerpt (Iv.)

Source: Internet
Author: User

Original Address http://www.cocoachina.com/ios/20150106/10840.html

Delay decompression

Once the image file is loaded it must be decoded, and the decoding process is a fairly complex task that takes a very long time. The decoded image will also use quite a lot of memory.

The CPU time used to load is different depending on the image format compared to decoding. For PNG images, the load will be longer than JPEG because the file may be larger, but the decoding will be relatively fast, and Xcode will decode the PNG image and then introduce the project. JPEG images are smaller and faster to load, but the decompression steps take longer, because the JPEG decompression algorithm is more complex than the zip-based PNG algorithm.

When loading a picture, iOS usually delays the time it takes to unzip the image until it is loaded into memory. This will affect performance as you prepare to draw the picture, because it needs to be decompressed before drawing (which is usually the time consuming problem).

The simplest approach is to use UIImage's +imagenamed: method to avoid delay loading. Unlike +imagewithcontentsoffile: (and other uiimage loading methods), this method extracts the image immediately after loading it (just like the benefits we talked about earlier in this chapter). The problem is +imagenamed: only the images from the app resource bundle are valid, so the user-generated picture content or the downloaded image is not available.

Another way to load an image immediately is to set it to the layer content, or the Image property of the Uiimageview. Unfortunately, this also needs to be performed on the main thread, so there is no performance improvement.

The third way is to bypass Uikit and use the ImageIO framework as follows:

Nsinteger index =*imageurl =ID=0*image = [ UIImage Imagewithcgimage:imageref]; Cgimagerelease (IMAGEREF); Cfrelease (source);

This allows you to create a picture using Kcgimagesourceshouldcache, force the image to be unpacked immediately, and then retain the extracted version for the life of the picture.

The last way to do this is to load the image with Uikit, but immediately know Cgcontext. Pictures must be extracted before drawing, so it is mandatory to understand the timeliness of pressure. The advantage is that drawing pictures can be performed by a background thread (for example, the load itself) without blocking the UI.

There are two ways to render a picture in advance for forced decompression:

    • Draws a pixel of a picture into a pixel-sized cgcontext. This still extracts the entire picture, but the drawing itself does not consume any time. The advantage is that the loaded picture is not optimized for drawing on a particular device, so it can be drawn at any point in time. Also, iOS can discard the extracted images to save memory.

    • Draw the entire picture into the Cgcontext, discard the original picture, and replace it with a new picture from the context content. This requires more complex calculations than a single pixel, but the resulting picture will be optimized for drawing, and because the original compressed image is discarded, iOS will not be able to discard any uncompressed images at any time to save memory.

It is important to note that Apple recommends not using these tricks to bypass the standard image decompression logic (so they choose to use the default processing), but if you use a lot of large graphs to build the application, then if you want to improve performance, you can only play with the system.

If you don't use +imagenamed: then drawing the entire picture to Cgcontext is probably the best way to do it. Although you may think that the extra drawing is not very high compared to other decompression techniques, the newly created image (optimized on a particular device) may be faster than the original picture.

Similarly, if you want to display a picture in a container that is smaller than the original size, then one-time re-drawing to the correct size in the background thread will be more efficient than zooming in every display (although in this case the image we load is rendered in the correct size, no extra optimizations are required).

If you modify the-collectionview:cellforitematindexpath: method to redraw the picture (listing 14.3), you will find that the slide is smoother.

-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (Nsindexpath*) Indexpath?{    //dequeue CellUicollectionviewcell *cell = [CollectionView dequeuereusablecellwithreuseidentifier:@"Cell"Forindexpath:indexpath]; ...    //switch to Background thread    Dispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_low, 0), ^{ //Load ImageNsinteger index =Indexpath.row; NSString*imagepath =Self.imagepaths[index]; UIImage*image =[UIImage Imagewithcontentsoffile:imagepath]; //Redraw image using device context        uigraphicsbeginimagecontextwithoptions (imageView.bounds.size, YES, 0);        [Image DrawInRect:imageView.bounds];        Image = uigraphicsgetimagefromcurrentimagecontext ();        Uigraphicsendimagecontext (); //set image on main thread, but only if index still matches upDispatch_async (Dispatch_get_main_queue (), ^{            if(Index = =imageview.tag) {imageview.image=image;    }        });    }); returncell;}

The stage of animation

Core animation is at the heart of iOS: It is used both within and between apps. A simple animation may display the contents of multiple apps synchronously, such as when using gesture switching between multiple programs on the ipad, which causes multiple programs to appear on the screen at the same time. It does not make sense to implement it in a specific application because it is not possible to do so in iOS (the app is managed by the sandbox and cannot access other views).

animations and on-screen combinations of layers are actually managed by a separate process, not your application. This process is called rendering services. The iOS5 and previous versions are the springboard process (while managing the main screen of iOS). The version after IOS6 is called backboard.

When you run an animation, the process is broken by four separate stages:

    • Layout-This is the stage for preparing your view/layer hierarchy, and for setting layer properties (position, background color, border, and so on).

    • Show-This is the stage where the layer's hosted picture is drawn. Drawing may involve your-drawrect: and-drawlayer:incontext: The call path of the method.

    • Prepare-This is the stage in which core animation prepares to send the animated data to the rendering service. This is also the point at which core animation will perform some other transaction such as decoding the picture that will be displayed during the animation.

    • Commit-This is the final stage where Core animation packages all layers and animated properties and then sends it to the rendering service via IPC (internal processing communication) for display.

But these stages only happen within your application, and there's still more work before the animations appear on the screen. Once packaged layers and animations reach the render service process, they are deserialized to form another layer tree called the Render tree (mentioned in the first chapter, "Layer Tree"). Using this tree structure, the rendering service works on each frame of the animation as follows:

    • Calculate intermediate values for all layer properties, set OpenGL geometry (textured triangles) to perform rendering

    • Render a visible triangle on the screen

so there are six stages , and the last two stages are repeated during the animation. The first five phases are processed at the software level (via the CPU) and only the last one is executed by the GPU . And, you really can only control the first two stages : layout and display. The Core animation framework handles the rest of the transaction internally, and you can't control it.

This is not a problem, because in the layout and display phase, you can decide which CPU to perform and what to do with the GPU. So how do you judge it?

GPU-related operations

But there are some things that can degrade (GPU-based) layer drawing, such as:

    • Too many geometries-this happens when too many triangles are needed to do transformations to cope with the rasterization of the processor. The graphics chip of a modern iOS device can handle millions of triangles, so the geometry in the core animation is not the bottleneck of the GPU. But because layers are sent to the render server via IPC before display (the layer is actually a particularly heavyweight object made up of many small objects), too many layers can cause CPU bottlenecks. This limits the number of layers that are displayed at once (see "CPU-related operations" later in this chapter).

    • Redraw-mainly caused by overlapping translucent layers. The GPU's fill ratio (the ratio of color-filled pixels) is limited, so you need to avoid redrawing (each frame fills multiple times with the same pixel). On modern iOS devices, the GPU handles repainting, and even the iphone 3GS can handle a redraw ratio of up to 2.5, while still maintaining a 60 frame rate rendering (which means you can draw a half-full screen of redundant information without compromising performance), and new devices can handle more.

    • Off-screen drawing-This occurs when you cannot draw directly on the screen and must be drawn into the context of the off-screen picture. Off-screen drawing occurs on CPU-or GPU-based rendering, or allocating additional memory for off-screen images, and switching the drawing context, which degrades GPU performance. The use of specific layer effects, such as rounded corners, layer masks, shadows, or layer rasterization, forces the core animation to render off-screen rendering of the layer in advance. But that doesn't mean you need to avoid using these effects, just understand that this can have a negative impact on performance.

    • Oversized picture-If the view draws a texture that exceeds the GPU-supported 2048x2048 or 4096x4096 size, you must use the CPU to pre-preprocess the picture before each layer is displayed, as well as degrade performance.

CPU-related operations

Most CPUs that work in core animation occur before the animation starts. This means it doesn't affect the frame rate, so it's good, but he will delay the start of the animation and make your interface look dull.

The following CPU operation will delay the start time of the animation:

    • Layout calculation-If your view hierarchy is too complex, the calculation layer frame rate consumes a portion of the time when the view is rendered or modified. In particular, the automatic layout mechanism using IOS6 is particularly noticeable, and it should be stronger than the old version of the automatic tuning logic to enhance the CPU's work.

    • View Lazy Loading-iOS will only load when the view controller's view is displayed on the screen. This is good for memory usage and program startup time, but many of the work that is caused by pressing a button will not be able to respond in a timely manner until it is rendered to the screen. For example, the controller obtains data from the database, or the view is loaded from a nib file, or a picture display involving IO (see subsequent "IO Related Operations") is much slower than normal CPU operation.

    • Core Graphics Drawing-If the view implements the-drawrect: method, or Calayerdelegate-drawlayer:incontext: method, Then there is a huge performance overhead before anything can be drawn. To support arbitrary drawing of the content of the layer, the Core animation must create a medium-sized, memory hosted picture. Then once the drawing is finished, the image data must be passed through the IPC to the render server. On this basis, the Core graphics will be very slow to draw, so it is not very good to do this in a very demanding performance scenario.

    • Unzip Pictures-png or JPEG compressed picture files are much smaller than the same-quality bitmaps. But before the picture is drawn to the screen, it must be expanded to a full uncompressed size (usually equal to the image width x length x 4 bytes). To save memory, iOS usually does not decode the image until it is actually drawn (chapter 14, "Picture io" is discussed in more detail). Depending on how you load the image, the first time you assign a value to the layer's content (either directly or indirectly using Uiimageview) or draw it into the core graphics, you need to unzip it, so that for a larger picture, it will take a certain amount of time.

When the layer is successfully packaged and sent to the render server, the CPU still has to do the following: In order to display the layers on the screen, the Core animation must be converted to textured triangles by OpenGL loops for each visible layer of the rendered tree. Because the GPU does not know any structure of the core animation layer, it has to be done by the CPU. The CPU involved in the work is proportional to the number of layers, so if there are too many layers in your hierarchy, it will cause the CPU to render without a frame, even if these things are not controllable by your application.

Ios--core Animation Knowledge Excerpt (Iv.)

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.