创建带阴影,有圆角的UIView的正确方式

本文介绍了一种使用CoreGraphics替代UIView图层属性以提高阴影绘制性能的方法。通过自定义UIView子类,采用CoreGraphics进行圆角和阴影绘制,有效避免了在UITableView等可滚动视图中出现的性能问题。

本文翻译自:Rounded UIView with shadow, the right way

241117030675969.png

我经常看到有人使用 UIView 的 layer图层来创建一个圆角或者阴影。代码类似这样:

[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 上时(或者任何可以移动的视图上时),滚动会有明显的卡顿和不顺畅,这是你不想要的。如果你想动画显示或者移动一个视图,避免像上面这样创建圆角或者阴影。

拜见 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);
}

转载于:https://www.cnblogs.com/YungMing/p/4362287.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值