The three----optimization view of view drawing optimization in Android

Source: Internet
Author: User

This article original, reproduced please indicate the source: http://blog.csdn.net/qinjuning


Translation three:

Optimizing views




For more information on how to design a custom view and respond to touch time, see Android Developer:

Address: http://developer.android.com/training/custom-views/index.html

This article translated address: optimizing the View



With the previous study, the well-designed view is now capable of responding to gestures and transitions between states, and you must ensure that the view

Runs smoothly and quickly. To avoid slow UI effects or running pauses, you must make sure that your animations are running at 60 frames per second.

As little as possible.


To speed up the view, reduce unnecessary code from those activities that are called frequently. Start drawing in the OnDraw () method, it will give you the largest

Benefit. Especially low, you should also reduce the memory allocation in the OnDraw () method, because any memory allocations can cause memory recycling, which will

Cause incoherence. Assigns an object between initialization or animation. Never allocate memory while the animation is running.


On the other hand, you need to reduce the overhead in the OnDraw () method and call the OnDraw () method only when needed. Typically the invalidate () method invokes the

OnDraw () method, thus reducing unnecessary calls to invalidate (). If possible, the overloaded version that calls it is the invalidate () with parameters

Method instead of the invalidate () method without a parameter. The method with the parameter invalidate () can make the draw process more efficient, and reduce the drop on the rectangle

The outer view of the area (the area specified by the parameter) does not have to be redrawn.


Note, the three overloaded versions of Invalidate () are:

1. Publicvoid invalidate (Rect dirty)
2, publicvoid invalidate (int l, int t, int r, int b)

3. Publicvoid invalidate ()


Another high-cost operation is the layout process. Any time you call the Requestlayout () method on the view, the Android UI framework

All need to traverse the entire view tree to determine the size of each view they occupy. If there is any conflict during the measure process, it may be traversed more than once

View tree. UI designers sometimes create deeper viewgroup to achieve some effect. But these deep-seated view trees can trigger efficiency.

Problem. Make sure your view tree level is as shallow as possible.


If you have a UI design that is complex, you should consider designing a custom ViewGroup to implement the layout process. Unlike the built-in view controls,

A custom view can assume the size and shape of each of its child view, while avoiding the measure process for each child view. Piechart

Shows how to inherit the ViewGroup class. Piechart with child view, but it never measure them. Instead, it is based on its own layout algorithm

To set the size of each child view directly.

As shown in the following code:

[Java]View Plaincopyprint?
  1. /**
  2. * Custom view that shows a pie chart and, optionally, a label.
  3. */
  4. Public class Piechart extends ViewGroup {
  5. ...
  6. //  
  7. //measurement functions. This example uses a simple heuristic:it assumes that
  8. //The pie chart should is at least as wide as its label.
  9. //  
  10. @Override
  11. protected int getsuggestedminimumwidth () {
  12. return (int) mtextwidth * 2;
  13. }
  14. @Override
  15. protected int getsuggestedminimumheight () {
  16. return (int) mtextwidth;
  17. }
  18. @Override
  19. protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {
  20. //Try for a width based in our minimum
  21. int minw = getpaddingleft () + getpaddingright () + getsuggestedminimumwidth ();
  22. int w = Math.max (MINW, Measurespec.getsize (Widthmeasurespec));
  23. //Whatever The width ends up being, ask for a height, this would let the pie
  24. //Get as big as it can
  25. int minh = (W-(int) mtextwidth) + getpaddingbottom () + getpaddingtop ();
  26. int h = math.min (Measurespec.getsize (Heightmeasurespec), Minh);
  27. Setmeasureddimension (W, h);
  28. }
  29. @Override
  30. protected void OnLayout (boolean changed, int L, int T, int R, int b) {
  31. //Do nothing. Don't call the superclass method--that would start a layout pass
  32. //On the This view ' s children.  Piechart lays out it children in onsizechanged ().
  33. }
  34. @Override
  35. protected void onsizechanged (int W, int h, int oldw, int oldh) {
  36. super.onsizechanged (W, H, OLDW, OLDH);
  37. //  
  38. //Set dimensions for text, pie chart, etc
  39. //  
  40. // account for padding
  41. ...
  42. //Lay out the "child view" that actually draws the pie.
  43. Mpieview.layout (int) Mpiebounds.left,
  44. (int) mpiebounds.top,
  45. (int) mpiebounds.right,
  46. (int) mpiebounds.bottom);
  47. Mpieview.setpivot (Mpiebounds.width ()/ 2, Mpiebounds.height ()/ 2);
  48. Mpointerview.layout (0, 0, W, h);
  49. Ondatachanged ();
  50. }
  51. }



Using hardware acceleration


After Android 3.0, Android 2D graphics library can use GPU (graphics processing Unit) acceleration on most Android devices. GPU Hardware

Acceleration can greatly optimize most applications, but it is not an optimal choice for every application. Android Framework gives you whether in the application

Use hardware-accelerated control forces.


<< How hardware acceleration >> shows how to use hardware acceleration in application, Activity, window levels. It is important to note that

We must manually set the application API level to 11 or higher in the configuration file, which is configured as follows in Androidmanifest.xml:
<USES-SDK android:targetsdkversion= "one"/>


Once you turn on hardware acceleration, you may not see an increase in efficiency. Mobile GPUs is adept at handling specific tasks, such as: scaling, rotating,

Pan the picture. It also has some tasks that are not good at handling, such as drawing lines or curves. As the saying goes, make the GPU

Deal with tasks that it excels at, and reduce the processing of weak tasks.


In the Piechart sample, for example, drawing a circle is relatively resource-intensive. The redraw caused by each rotation causes the UI to be sluggish.

The workaround is to have the view render the circle, and set the view's LAYER TYPE property to Layer_type_hardware, so the GPU

Ability to cache static images. In the example, the view is present as an inner class of the Piechart class, reducing the code overhead in order to implement this method.

[Java]View Plaincopyprint?
  1. Private class Pieview extends View {
  2. Public Pieview (context context) {
  3. super (context);
  4. if (!isineditmode ()) {
  5. Setlayertype (View.layer_type_hardware, null);
  6. }
  7. }
  8. @Override
  9. protected void OnDraw (canvas canvas) {
  10. Super.ondraw (canvas);
  11. For (Item it:mdata) {
  12. Mpiepaint.setshader (It.mshader);
  13. Canvas.drawarc (Mbounds,
  14. 360-it.mendangle,
  15. It.mendangle-it.mstartangle,
  16. true, mpiepaint);
  17. }
  18. }
  19. @Override
  20. protected void onsizechanged (int W, int h, int oldw, int oldh) {
  21. Mbounds = New RECTF (0, 0, W, h);
  22. }
  23. RECTF Mbounds;
  24. }



After the change, the PieChart.PieView.onDraw () method is called only when the view is first displayed. In the application's other

Time, the drawn image will be cached as a picture, and the GPU will rotate any image when redrawn.


However, this is only a medium of compromise. Cached images are a hardware layer that causes video memory overhead and video memory is a restricted

Resources. For this reason, on the final version of Piechart.pieview, the Layer Type property is set only if the user is sliding

Layer_type_hardware. At other times, just set its LAYER TYPE property to Layer_type_hardware, which

Allows the GPU to stop caching pictures.



Finally, don't forget to analyze your code. Optimization techniques made on one view may have a bad effect on other view.

The three----optimization view of view drawing optimization in Android

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.