App开发中页面有的时候会比较复杂,视图越简单性能一般越快,但是UI不是由开发决定,当页面视图嵌套太多,很容易出现滑动卡顿掉帧的现象. Color Blended Layers 通过模拟器Debug可以查看视图中颜色混合.如果视图中的颜色混合越多,那么GPU通过混合纹理计算出像素的RGB值需要消耗的时间就越长,GPU的使用率就越高,可以通过减少颜色混合来提升滑动的流畅性.
UILabel
像素混合是只同一个区域两个不同的View的叠加,顶部视图的颜色有不透明度,那么顶部视图会和底部视图发生颜色混合,为了避免像素混合,尽可能地为顶部视图设置背景色,且设置opaque为YES,这样会减少GPU的计算.
StoryBoard创建UILabel,UIViewController的View相当于底部视图:
<pre><code>`
self.showLabel.opaque = YES;
// self.showLabel.layer.masksToBounds = YES;
UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 300, 200, 100)];
testLabel.backgroundColor = [UIColor darkGrayColor];
testLabel.text = @"简单-FlyElephant";
// testLabel.opaque = YES;
testLabel.font = [UIFont systemFontOfSize:14];
testLabel.textColor = [UIColor blackColor];
// testLabel.layer.masksToBounds = YES;
[self.view addSubview:testLabel];
`</code></pre>
通过模拟器Debug下的Color Blended Layers观察如下:
我们发现设置Label的opaque并没有效果,当我们取消注释,将Label的
masksToBounds设置为YES,效果如下:
绿色越多,代表混合的情况越少,红色越多App UI急需改进.
UILabel在iOS8以前,UILabel使用的是CALayer作为底图层,而在iOS8开始,UILabel的底图层变成了_UILabelLayer,绘制文本的方式发生了改变.因此opaque设置无效.
UITableView
项目中UITableView使用的频率一般都比较高,我们创建一个简单UITableView,自定义UITableViewCell看一下混合效果:
主要实现代码:
<pre><code>`
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 20;
}-
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (indexPath.row%2 == 0) {
cell.contentLabel.text = @"简书-FlyElephant";
} else {
cell.contentLabel.text = @"FlyElephant";
}
return cell;
} (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 60.0f;
}</code></pre> 通过设置Cell的背景颜色可以消除像素混合: <pre><code>
cell.backgroundColor = [UIColor whiteColor];
cell.contentLabel.backgroundColor = cell.backgroundColor;
cell.contentLabel.layer.masksToBounds = YES;// 中文字体需要此设置`</code></pre>