IOS Core Animation Advanced techniques-Layer Performance optimization

Source: Internet
Author: User
Tags transparent color

On 11 chapters:

    1. Layer Tree
    2. Layer's Homestay Map
    3. Layer geometry
    4. Layer Visual effects
    5. Layer transformations
    6. Dedicated layers
    7. Implicit animations
    8. An explicit animation
    9. Layer Time
    10. Layer buffering
    11. Timer-based animations

This essay focuses on layer performance optimizations.

CPU VS GPU:

    • There are two ways of drawing and animating:

1.CPU (central processing Unit)

2.GPU (graphics processing device)

      • In image processing, the normal GPU is more efficient than the CPU, but when the GPU runs out of resources, performance starts to fall (even if the CPU is not fully occupied)
      • Most animation performance optimizations are about intelligently leveraging the GPU and CPU so that they do not exceed the load.

Rendering Service:

    • Animations and on-screen combinations of layers are actually managed by a separate process, not your application. This process is called rendering services.

Run an animation, divided into four stages:

    • 1. Layout
      • Prepare the hierarchy of your view/layer, and set the stage for layer properties (position, background color, border, and so on)
    • 2. Display
      • The layer's homestay map is drawn, drawing a path that may involve-drawrect: and-drawlayer:incontext: The method's invocation.
    • 3. Preparation
      • Core animation ready to send animated data to the stage of rendering service
    • 4. Submit
      • At the final stage, Core animation packages all layers and animation properties and then sends it to the rendering service via IPC (internal processing communication) for display.
      • Once packaged layers and animations reach the render service process, they are deserialized to form another layer tree called the render tree. Using this tree structure, the rendering service works on each frame of the animation as follows:
    • 5. Calculate intermediate values for all layer properties, set OpenGL geometry (textured triangles) to perform rendering
    • 6. Render visible triangles on the screen
      • 5 6 stage repeats during animation
      • 1-5 stages in software-level processing (via CPU)
      • 6 Stages in GPU execution
      • and can only control the 1・2 phase:
        • Layout and display
      • So you can:
        • In the layout and display phase, decide which CPU to perform and what to do with the GPU

GPU-related operations:

    • Most Calayer properties are plotted using GPUs, such as:
    • The color of the layer background or border
    • Will reduce the things that are based on GPU layer drawing:
      • 1. Too many geometric structures
        • When the layer is sent to the render server via IPC before it is displayed, too many layers can cause CPU bottlenecks, limiting the number of layers shown at one time
      • 2. Redraw
        • Mainly caused by overlapping translucent layers
      • 3. Off-screen drawing
        • Occurs when you cannot draw directly on the screen and must be drawn to the context of the off-screen picture
        • Allocating additional memory for off-screen images, and toggling the drawing context, which can degrade 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.
      • 4. Oversized pictures
        • The view draws a texture that exceeds the GPU-supported 2048x2048 or 4096x4096 size, and the CPU must pre-preprocess the picture before each layer is displayed, and it also degrades performance

CPU-related operations:

    • The CPU takes place before the animation starts and does not affect the frame rate, but he delays the start of the animation and makes your interface look dull.
    • The thing that will delay the time the CPU lets the animation start:
      • 1. Layout calculation
        • The view hierarchy is too complex, especially with the automatic layout mechanism using IOS6.
      • 2. View Lazy Loading
      • 3.Core Graphics Drawing
        • The view implements the-drawrect: method, or Calayerdelegate's-drawlayer:incontext: method, which produces a huge performance overhead before anything is drawn.
        • To support arbitrary drawing of the content of the layer, the Core animation must create a medium-sized, memory hosted picture.
        • Once the drawing is finished, the image data must be passed through the IPC to the render server. The Core graphics will become very slow to draw
      • 4. Unzip the image

IO related operations:

  • IO is slower than memory access, so if the animation involves Io, it is a big problem.
  • Demonstration examples:
    • Create a simple app that displays a list of simulated contact names and avatars
    • Load pictures in real time, not with –imagenamed: preload
    • Add some layer shadows to make the list appear more realistic
      • #import "ViewController.h"
      • #import <QuartzCore/QuartzCore.h>
      • @interface Viewcontroller () <UITableViewDataSource>
      • @property (nonatomic, strong) Nsarray *items;
      • @property (nonatomic, weak) Iboutlet UITableView *tableview;
      • @end
      • @implementation Viewcontroller
      • -(NSString *) randomname
      • {
      • Nsarray *first = @[@ "Alice" @ "Bob" @ "Bill" @ "Charles" @ "Dan" @ "Dave" @ "Ethan" @ "Frank"];
      • Nsarray *last = @[@ "appleseed", @ "Bandicoot", @ "Caravan", @ "dabble", @ "Ernest", @ "Fortune"];
      • Nsuinteger index1 = (rand ()/(double) int_max) * [First Count];
      • Nsuinteger index2 = (rand ()/(double) int_max) * [last count];
      • return [NSString stringwithformat:@ "%@%@", First[index1], Last[index2]];
      • }
      • -(NSString *) Randomavatar
      • {
      • Nsarray *images = @[@ "Snowman", @ "Igloo", @ "Cone", @ "Spaceship", @ "Anchor", @ "Key"];
      • Nsuinteger index = (rand ()/(double) int_max) * [images count];
      • return Images[index];
      • }
      • -(void) viewdidload
      • {
      • [Super Viewdidload];
      • Set up data
      • Nsmutablearray *array = [Nsmutablearray array];
      • for (int i = 0; i <; i++) {
      • Add Name
      • [Array addobject:@{@ "name": [Self randomname], @ "image": [Self Randomavatar]}];
      • }
      • Self.items = array;
      • Register Cell Class
      • [Self.tableview Registerclass:[uitableviewcell class] forcellreuseidentifier:@ "Cell"];
      • }
      • -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section
      • {
      • return [Self.items Count];
      • }
      • -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath
      • {
      • Dequeue cell
      • UITableViewCell *cell = [Self.tableview dequeuereusablecellwithidentifier:@ "cell" forindexpath:indexpath];
      • Load image
      • Nsdictionary *item = Self.items[indexpath.row];
      • NSString *filepath = [[NSBundle mainbundle] pathforresource:item[@ "image"] oftype:@ "PNG"];
      • Set image and text
      • Cell.imageView.image = [UIImage imagewithcontentsoffile:filepath];//loading picture in real time
      • Cell.textLabel.text = item[@ "name"];
      • Set Image Shadow
      • Cell.imageView.layer.shadowOffset = Cgsizemake (0, 5);
      • Cell.imageView.layer.shadowOpacity = 0.75;
      • Cell.clipstobounds = YES;
      • Set Text Shadow
      • Cell.textLabel.backgroundColor = [Uicolor Clearcolor];
      • Cell.textLabel.layer.shadowOffset = Cgsizemake (0, 2);
      • cell.textLabel.layer.shadowOpacity = 0.5;
      • return cell;
      • }
    • /*
    • The above code runs when the test tool finds that the frame rate is only 14FPS
    • Intuitively, we suspect that the performance bottleneck should be loaded in the picture. So I want to use GCD to load the picture asynchronously and then cache ...
    • In fact through the instruments tool analysis:
      • Time Profiler tool (see Tools for each task using CPU rate):
        • -tableview:cellforrowatindexpath: The total CPU time utilization is only ~28% (that is, where the avatar image is loaded), very low.
        • So the suggestion is that Cpu/io is not really a limiting factor.
      • OpenGL ES Driver Tool (tool for detecting GPU utilization):
        • The value of rendering service utilization reaches 51% and 63%, which is high.
        • It looks like the GPU needs to do a lot of work to render the contact list.
      • Core Animation Debug Tool options (check screen):
      • Color blended layers option (mixed draw detection):
        • All red parts of the screen mean high-level blending of the character label view
        • This is normal because we set the background to a transparent color to show the shadow effect. (Setting transparent properties can degrade GPU performance)
        • This explains why the rendering utilization is so high.
      • Color offscreen-rendered Yellow option (off-screen paint detection):
        • The yellow area represents the off-screen drawing and finds that all table cell contents are drawn off-screen.
        • is because we add a shadow effect to the picture and the tag view
        • Remove the shadow from the code and find that the frame rate is up to a + FPS, sliding smoothly
    • */
  • How do I keep the shadow effect without compromising performance?
    • Because each line of characters and avatars does not need to be changed when each frame is refreshed, the UITableViewCell layer is ideal for caching.
    • We can use Shouldrasterize to cache layer content. This will cause the layer to render once after it is off the screen and save the results until the next time you use it to update
    • Demonstration Example://using shouldrasterize to improve performance
      • -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath
      • {
      • Dequeue cell
      • UITableViewCell *cell = [Self.tableview dequeuereusablecellwithidentifier:@ "Cell"
      • Forindexpath:indexpath];
      • ...
      • Set Text Shadow
      • Cell.textLabel.backgroundColor = [Uicolor Clearcolor];
      • Cell.textLabel.layer.shadowOffset = Cgsizemake (0, 2);
      • cell.textLabel.layer.shadowOpacity = 0.5;
      • Rasterize
      • Cell.layer.shouldRasterize = yes;//Focus
      • Cell.layer.rasterizationScale = [UIScreen mainscreen].scale;
      • return cell;
      • }
    • /*
    • We still draw the contents of the layer off the screen, but due to the explicit disabling of rasterization, Core animation caches the results for the drawing, thus improving performance.
    • Through the Core Animation tool
    • Color Hits Green and Misses red options:
    • The green area represents the off-screen drawing, mostly green,
    • Red represents non-off-screen drawing, and when sliding, the screen flashes red.
    • So our original idea was wrong. Picture loading is not really a bottleneck, and trying to put it into a complex multiline preempted and cache implementation will be futile.
    • So it's a good habit to verify the problem before you fix it!
    • */

IOS Core Animation Advanced techniques-Layer Performance optimization

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.