1.过渡绘制
Overdraw(过度绘制)描述的是屏幕上的某个像素在同一帧的时间内被绘制了多次。在多层次重叠的UI结构里面,如果不可见的UI也在做绘制的操作,会导致某些像素区域被绘制了多次。这样就会浪费大量的CPU以及GPU资源。
当设计上追求更华丽的视觉效果的时候,我们就容易陷入采用越来越多的层叠组件来实现这种视觉效果的怪圈。这很容易导致大量的性能问题,为了获得最佳的性能,我们必须尽量减少Overdraw的情况发生。
幸运的是,我们可以通过手机设置里面的开发者选项,打开Show GPU Overdraw的选项,可以观察UI上的Overdraw情况。
蓝色,淡绿,淡红,深红代表了4种不同程度的Overdraw情况,我们的目标就是尽量减少红色Overdraw,看到更多的蓝色区域。
产生的主要原因是:
- 不必要的背景颜色或背景图片
- 被遮挡的不可见部分
2.不必要的背景色或背景图片
优化前后对比主要优化点:
- 设置window的背景为null
//The Theme's windowBackgroud is masked by the opaque backgroud of the activity,and
//the windowBackgroud causes an unnecessary overdraw.Nullifying the windowBackgroud
//removes the overdraw.
getWindow().setBackgroundDrawable(null); - 清除xml不必要的background
- 按需显示占位背景图片
// Display the chat author's avatar (a droid image) and a background color associated with
// the author.
if(chat.getAuthor().getAvatarId()==0){
Picasso.with(getContext()).load(android.R.color.transparent).into(chat_author_avatar);
chat_author_avatar.setBackgroundColor(chat.getAuthor().getColor());
}else{
Picasso.with(getContext()).load(chat.getAuthor().getAvatarId()).into(chat_author_avatar);
chat_author_avatar.setBackgroundColor(Color.TRANSPARENT);
}
3.被遮挡的不可见部分
优化前onDraw方法下面的代码显示了如何通过clipRect来解决自定义View的过度绘制,提高自定义View的绘制性能:
下面是优化过后的效果:
蛋妞码农