hasOverlappingRendering 一个性能优化的方法

来源:互联网 发布:淘宝一键上传宝贝 编辑:程序博客网 时间:2024/06/09 16:48

android的View类里有一个可以继承的方法hasOverlappingRendering()。


    /**     * Returns whether this View has content which overlaps.     *     * <p>This function, intended to be overridden by specific View types, is an optimization when     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to     * an offscreen buffer and then composited into place, which can be expensive. If the view has     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value     * directly. An example of overlapping rendering is a TextView with a background image, such as     * a Button. An example of non-overlapping rendering is a TextView with no background, or an     * ImageView with only the foreground image. The default implementation returns true; subclasses     * should override if they have cases which can be optimized.</p>     *     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}     * necessitates that a View return true if it uses the methods internally without passing the     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>     *     * <p><strong>Note:</strong> The return value of this method is ignored if {@link     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>     *     * @return true if the content in this view might overlap, false otherwise.     */    @ViewDebug.ExportedProperty(category = "drawing")    public boolean hasOverlappingRendering() {        return true;    }

该方法用来标记当前view是否存在过度绘制,存在返回ture,不存在返回false,默认返回为true。

知道了这些就可以用该方法了,在保证该View不存在过度绘制的情况下,继承该方法,直接返回false即可。


但是对于一个有追求的开发者,更应该研究明白继承这个方法来性能优化的原理,只知其然不知其所以然是提高不了自己的水平的。下面就来说说这个方法具体是怎么用来性能优化的。


在android的View里有透明度的属性,当设置透明度setAlpha的时候,android里默认会把当前view绘制到offscreen buffer中,然后再显示出来。 这个offscreen buffer 可以理解为一个临时缓冲区,把当前View放进来并做透明度的转化,然后在显示到屏幕上。这个过程是消耗资源的,所以应该尽量避免这个过程。


避免这个过程可以分很多种情况,常见的比如没有背景的TextView,就可以直接设置文字颜色,而不是设置整体alpha;ImageView设置图片透明度setImageAlpha,自定义View设置绘制时的paint的透明度。


而当继承了hasOverlappingRendering()方法返回false后,android会自动进行合理的优化,避免使用offscreen buffer。


需要注意的是,当调用forceHasOverlappingRendering(boolean b)后这个方法就会被忽略。





1 0
原创粉丝点击