我经常看到人们使用 HUGE 性能影响的视图层来创建圆角或阴影效果。就像这样:
[v.layer setCornerRadius:30.0f];
[v.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[v.layer setBorderWidth:1.5f];
[v.layer setShadowColor:[UIColor blackColor].CGColor];
[v.layer setShadowOpacity:0.8];
[v.layer setShadowRadius:3.0];
[v.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
.....
这将会对性能产生巨大的影响,特别是阴影效果。将这样的视图放在UITableView(或者移动任何东西)中会创建一种类似于Android的滚动体验,你不想要那样的结果。如果需要对视图进行动画或移动,请避免以任何方式创建圆角或投影阴影等效果!
认识核心绘图:我创建了一个简单的UIView子类来向您展示如何以稍微不同的方式实现相同的结果。它使用Core Graphics来绘制视图,并且与上面的代码相比,它不会影响性能。
以下是绘图代码:
- (void)drawRect:(CGRect)rect
{
CGContextRef ref = UIGraphicsGetCurrentContext();
CGRect contentRect = CGRectInset(rect, _shadowRadius, _shadowRadius);
UIBezierPath *roundedPath = [UIBezierPath bezierPathWithRoundedRect:contentRect cornerRadius:_cornerRadius];
CGContextSetFillColorWithColor(ref, _fillColor.CGColor);
CGContextSetShadowWithColor(ref, CGSizeMake(0.0, 0.0), _shadowRadius, _shadowColor.CGColor);
[roundedPath fill];
[roundedPath addClip];
CGContextSetStrokeColorWithColor(ref, [UIColor colorWithWhite:1.0 alpha:0.6].CGColor);
CGContextSetBlendMode(ref, kCGBlendModeOverlay);
CGContextMoveToPoint(ref, CGRectGetMinX(contentRect), CGRectGetMinY(contentRect)+0.5);
CGContextAddLineToPoint(ref, CGRectGetMaxX(contentRect), CGRectGetMinY(contentRect)+0.5);
CGContextStrokePath(ref);
}
请查看这篇博客:
http://damir.me/rounded-uiview-with-shadow-the-right-way,它与带有阴影的圆角UIView有关。
shadowOffset
阴影,但 iPhone 4 在绘制shadowOffset
阴影时会出现延迟和闪烁。 - Nate SymerrasterizationScale
可以带来更好的性能,但并非最佳。我在我的自定义键盘中使用它,但仍然会在开始时有一点卡顿。 - TomSawyer