App開發(fā)中頁面有的時候會比較復雜,視圖越簡單性能一般越快,但是UI不是由開發(fā)決定,當頁面視圖嵌套太多,很容易出現(xiàn)滑動卡頓掉幀的現(xiàn)象. Color Blended Layers 通過模擬器Debug可以查看視圖中顏色混合.如果視圖中的顏色混合越多,那么GPU通過混合紋理計算出像素的RGB值需要消耗的時間就越長,GPU的使用率就越高,可以通過減少顏色混合來提升滑動的流暢性.
UILabel
像素混合是只同一個區(qū)域兩個不同的View的疊加,頂部視圖的顏色有不透明度,那么頂部視圖會和底部視圖發(fā)生顏色混合,為了避免像素混合,盡可能地為頂部視圖設(shè)置背景色,且設(shè)置opaque為YES,這樣會減少GPU的計算.
StoryBoard創(chuàng)建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觀察如下:

我們發(fā)現(xiàn)設(shè)置Label的opaque并沒有效果,當我們?nèi)∠⑨?,將Label的
masksToBounds設(shè)置為YES,效果如下:

綠色越多,代表混合的情況越少,紅色越多App UI急需改進.
UILabel在iOS8以前,UILabel使用的是CALayer作為底圖層,而在iOS8開始,UILabel的底圖層變成了_UILabelLayer,繪制文本的方式發(fā)生了改變.因此opaque設(shè)置無效.
UITableView
項目中UITableView使用的頻率一般都比較高,我們創(chuàng)建一個簡單UITableView,自定義UITableViewCell看一下混合效果:

主要實現(xiàn)代碼:
<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> 通過設(shè)置Cell的背景顏色可以消除像素混合: <pre><code>
cell.backgroundColor = [UIColor whiteColor];
cell.contentLabel.backgroundColor = cell.backgroundColor;
cell.contentLabel.layer.masksToBounds = YES;// 中文字體需要此設(shè)置`</code></pre>
