android--Hardware Acceleration (Hardware acceleration (Hardware acceleration)

Source: Internet
Author: User

Starting with Android3.0 (API level 11), the Android 2D rendering pipeline provides better support for hardware acceleration. all of the drawing operations performed by hardware acceleration are done using the GPU on the View object's canvas . Because enabling hardware acceleration increases the need for resources, such an application consumes more memory.

Hardware acceleration is turned on by default when the target API is greater than or equal to 14, but we can also display the turn on hardware acceleration. If your application uses only standard view and drawable, turning on global hardware acceleration does not cause any undesirable drawing effects. However, because hardware acceleration does not support all 2D drawing operations, turning on global hardware acceleration for those with custom view and draw calls can have an impact. For this problem, it is usually the pixel rendering that is abnormal or incorrect for those elements that are not visible. To avoid this problem, Android provides multiple levels of hardware acceleration (on or off), with specific visibility to control hardware acceleration.

If your application performs a custom drawing and turns on hardware acceleration, test it on a real machine with hardware acceleration to find the problem. Unsupported drawing operations describe hardware acceleration issues and how to resolve them.

Control hardware acceleration (controlling Hardware acceleration) Android provides the following four levels to control hardware acceleration:
    1. Application
    2. Activity
    3. Window
    4. View
Application level

In the app's Android manifest file, add the following attributes to the <application> element to enable hardware acceleration for the entire application:

<application android:hardwareaccelerated= "true" ...>
Activity level

If the application does not correctly use the global hardware acceleration that is turned on, it can also be controlled at the activity level. Use the android:hardwareaccelerated attribute in the <activity> element to enable or disable hardware acceleration at the activity level. The following example enables global hardware acceleration, but disables hardware acceleration for an activity:

<application android:hardwareaccelerated= "true" >    <activity .../>    <activity android: Hardwareaccelerated= "false"/></application>
Window level

If finer control is required, you can use the following code to enable hardware acceleration for a given window:

GetWindow (). SetFlags (    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

Note: In the current situation, hardware acceleration cannot be disabled at the window level.

View level

At run time, you can use the following code to suppress hardware acceleration for a separate View object:

Myview.setlayertype (view.layer_type_software, NULL);

Note: In the current situation, hardware acceleration cannot be turned on at the view level. The view layer has additional features in addition to hardware acceleration, see the view layer of this article for more information.

Determine if a View object is hardware accelerated

Sometimes it is useful to know whether the current view objects, especially those that are customized, are hardware-accelerated for the application. This is especially useful if the application does a lot of custom drawing operations, and not all operations are supported by the new render pipeline.

There are two different ways to check whether an application is hardware-accelerated:

    • View.ishardwareaccelerated (): The return value of the True,view object is bound to a hardware-accelerated window;
    • Canvas.ishardwareaccelerated (): The return value of the True,canvas object is hardware accelerated;

Android Graphics mode (Android Drawing Models)

When hardware acceleration is enabled, the Android framework takes on a new drawing mode, which uses the display list to render the application on the screen. Having a good understanding of display lists and how they affect your application is also useful for understanding how Android is drawing view objects without hardware acceleration. The following sections describe the software-and hardware-accelerated drawing modes.

Software-based drawing mode (software-based drawing model)

In the software's drawing mode, the View object is drawn in the following two steps:

    1. Invalidate the View hierarchy
    2. Drawing the View hierarchy

Whenever an application needs to update its UI part, it calls View#invalidate () (or a related variant of the Invalidate method) to make the UI content change. A failed message request is passed through the View object hierarchy to calculate the screen area (dirty area) that needs to be redrawn. The Android system then draws all areas that intersect the dirty area in the view hierarchy. Unfortunately, this drawing pattern has two drawbacks:

    1. The first problem is that in each drawing pass, this drawing pattern requires a lot of code execution . For example, if the application calls a button's invalidate () method, and the button is above another view object, the Android system will redraw the view object even if the View object does not change.
    2. Second problem, this kind of drawing mode can hide bugs in the application. Because the Android system redraws other view objects that intersect the dirty area, even if the invalidate () method on the View object is not called, the change in the contents of the View object may cause other view to be redrawn. When this happens, rely on another view object that is invalidated to get the appropriate behavior. This behavior can change every time you modify the application. For this reason, in order to influence the drawing code, you should always call the invalidate () method of the custom view object when modifying the data and state of the custom View object.

Note: When the View object's properties change, such as the background color or the text in the TextView object, Android automatically calls the View object's invalidate () method.

Hardware accelerated Drawing Mode (Hardware accelerated drawing model)

In this mode, the Android system will still use invalidate () and draw () to request a screen update and render the view, but the actual drawing operation differs from the software-based drawing mode. It immediately executes the drawing commands, which the Android system records in the internal display list, which contains the output of the drawing code for the View object hierarchy. Another optimization is that the Android system only needs to record and update the display list for the dirty area of the View object marked by the Invalidate () method call. A view object that is not invalidated can perform a simple redraw by republishing the previously recorded display list. This new drawing pattern consists of three stages:

    1. Invalidate the hierarchy for view
    2. Record and update display lists
    3. Draw a display list

With this pattern, it is not possible to rely on view#draw () execution of the intersecting dirty area. To make sure that the Android system records the display list of a View object, you must call the Invalidate () method, and if you forget to call the method, the View object will look the same as it was before the change occurs.

Using a display list is also good for improving the performance of animations, because setting special properties such as transparency, rotation, and so on, does not require that the target view object be invalidated (the system will do this automatically). This optimization also applies to view objects with a display list (any view object when the application is hardware accelerated). For example, if you have a linearlayout layout for a ListView object that contains a button object, the display list for the LinearLayout layout is as follows:

    • Drawdisplaylist (ListView)
    • Drawdisplaylist (Button)

Assuming that you want to change the transparency of a ListView object now, when you call the Setalpha (0.5f) method of the ListView object, the display list contains the following processing:

    1. Savelayeralpha (0.5);
    2. Drawdisplaylist (ListView);
    3. Restore;
    4. Drawdisplaylist (Button).

There is no drawing code to execute the complex ListView object. Instead, the system simply updates the display list of the LinearLayout object. In an application that does not have hardware acceleration enabled, the list (ListView) and its parent object will execute the drawing code again.

Hardware-accelerated operations are not supported

In hardware acceleration, the 2D rendering pipeline supports most of the drawing operations typically used for canvas, as well as some rarely used operations. All the drawing operations that are used to render the application are sent to the Android system, the default widgets and layouts, and some common visual effects such as reflection and tile texture are supported.

Here is a link-hardware-accelerated operations that are not supported at different API levels.

View Layers

in all versions of Android, by using the View object's drawing buffer, or by using the Canvas.savelayer () method, view has the ability to render to the off-screen (off-screen) buffer. Off-screen buffers or layers are used for a variety of purposes, enabling better performance when rendering complex animations or using composite effects. For example, you can use Canvas.savelayer () to achieve a fade-out effect by temporarily rendering a view object in a layer and then compositing it and the opacity factor onto the screen.

starting with Android3.0 (API level 11), Android provides more control over how and when to use the View.setlayertype () issue. This API carries two parameters: one is the type of the layer and the other is the optional paint 对象 , which describes how the layer should be synthesized. Use this Paint object to perform color filtering, special blending modes, or layer transparency. The view object is capable of using the following three layer types:

    • Layer_type_none:view objects are rendered in a normal way and are not returned by an off-screen cache. This type is the default behavior.
    • Layer_type_hardware: If the application is hardware-accelerated, then the view object is rendered in a hardware texture (texture) of the hardware. If hardware acceleration is not turned on, the behavior of this layer type is the same as Layer_type_software.
    • The Layer_type_software:view object is rendered in a bitmap in the software.

Select the layer type according to the following:

    1. Performance: Use the hardware layer type to render the view into a hardware texture. Once the view object is rendered to a layer, its drawing code is not executed until the invalidate () method of the View object is called. For some animations, such as alpha animations, you can use the layer directly, which is very efficient for the GPU.
    2. Visual effects: Use layer types (hardware or software) and a paint object to apply some special visual processing to a View object. For example, use the Colormatrixcolorfilter object to draw a black-and-white view object.
    3. Compatibility: Using the Software layer type forces a view object to be rendered in the software. If a hardware-accelerated view object (for example, if the entire application is hardware accelerated) renders a problem, it is an easy way to use the software layer type to solve the hardware rendering pipeline limitations.

View layers and animations

When the application is hardware accelerated, the hardware layer can deliver faster, smoother animations. When playing an animation with a complex drawing operation, it is not always possible to play at a speed of 60 frames per second. However, you can alleviate this situation by rendering the view object in a hardware texture using the hardware layer. The hardware texture can be used in an animated view so that when the View object renders an animation, it eliminates the redraw action required by the View object. It will not be redrawn until the View object's properties change (the Invalidate () method is called). If you run an animation in your application and do not get the desired smoothing results, consider enabling the hardware layer on the animation view.

When a view is returned from the hardware layer, some properties processed by the layer method are composited onto the screen. Because they do not need to invalidate and redraw the view object, setting these properties is very efficient. below is a list of how the affected layers are synthesized. Invoking these property sets results in an optimization of the invalidation process and does not redraw the target view object:

    1. Alpha: Change the transparency of layers;
    2. X,y,translation,translation: Change the position of the layer;
    3. Scalex,scaley: Change the size of the layer;
    4. Rotation,rotation,rotationy: Change the direction of the middle of 3D space;
    5. Pivotx,pivoty: Change the origin of the layer.

These properties are the names used when animating a view object with a Objectanimator object. If you want to access these properties, you call the appropriate set or Get method. For example, to modify the Alpha property, call the Setalpha () method. The following code shows the most efficient way to rotate a view object around the y-axis in 3D space:

View.setlayertype (view.layer_type_hardware, null); Objectanimator.offloat (View, "RotationY", and.). Start ();

Because the hardware layer consumes the display memory, it is highly recommended to enable the hardware layer only during animation playback, and disable the hardware layer after the animation has finished playing. The ability to use an animation listener to do this:

View.setlayertype (view.layer_type_hardware, null); Objectanimator animator = Objectanimator.offloat (View, "RotationY Animator.addlistener (New Animatorlisteneradapter () {    @Override public    void Onanimationend (animator Animation) {        view.setlayertype (view.layer_type_none, null);    }}); Animator.start ();

For more information on animating properties, see Property Animation.

Tips and Tricks

Choosing hardware-accelerated 2D graphics can improve performance, but in order to use the GPU effectively, you should design your application according to the following recommendations:

Reduce the number of view objects in your application

The more View objects The system draws, the slower it will be. This also applies to software rendering pipelines. One of the effective ways to reduce the view object is to optimize the UI.

Avoid over-plotting

Do not draw too many layers at the top of each other. Remove the Viewthat are completely obscured by other opaque view . A good principle for the current hardware is that the number of pixels per frame is not greater than 2.5 times times that of the number on the screen (as measured by the bitmap's transparent lattice count).

Do not create a render object in the drawing method

A common mistake is to create a new paint object or Path object each time the Render method is called. This enforces frequent garbage collection, which bypasses caching and optimizations in the hardware pipeline.

Do not edit shapes frequently

For complex shapes, such as paths and circles, they are rendered using a texture mask. Each time you create or modify a path, the hardware channel creates a new texture matte, which consumes a lot of resources.

Do not edit bitmaps frequently

Each time you change the bitmap content, it is uploaded to the GPU texture again for the next draw.

Be careful about using alpha-related methods

When using Setalpha (), alphaanimation, or objectanimator to make a View object translucent, a double fill rate is required to render to the off-screen cache. When applying a transparency effect on a large view object, consider setting the layer type of the View object to Layer_type_hardware.

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.