我经常看到人们使用巨大的性能影响视图的图层来创建圆角或阴影。像这样的东西:
[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-ish 滚动体验,你不希望这样。如果您需要动画或移动视图,请避免以任何方式创建圆角或阴影!
认识 Core Graphics
我创建了一个简单的 UIView 子类来向您展示如何以稍微不同的方式实现相同的结果。它使用 Core Graphics 来绘制视图,与上面的代码相比,它不会影响性能。
这是绘图代码:
- (void)drawRect:(CGRect)rect
{
CGContextRef ref = UIGraphicsGetCurrentContext();
/* We can only draw inside our view, so we need to inset the actual 'rounded content' */
CGRect contentRect = CGRectInset(rect, _shadowRadius, _shadowRadius);
/* Create the rounded path and fill it */
UIBezierPath *roundedPath = [UIBezierPath bezierPathWithRoundedRect:contentRect cornerRadius:_cornerRadius];
CGContextSetFillColorWithColor(ref, _fillColor.CGColor);
CGContextSetShadowWithColor(ref, CGSizeMake(0.0, 0.0), _shadowRadius, _shadowColor.CGColor);
[roundedPath fill];
/* Draw a subtle white line at the top of the view */
[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