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


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

    我经常看到有人使用 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);
    }
    
  • 相关阅读:
    003_&#x和ASCII的关系及URL中的中文转义
    001_机器学习的Hello world之MNIST手写数字识别模型
    Appnium安装-Mac平台
    Code Review 规范
    Spring AOP-xml配置
    JTLParser-linux上jmeter的jtl文件二次分析
    测试覆盖率Emma工具使用
    jmeter之java请求
    jmeter测试总结
    jstat监控gc情况
  • 原文地址:https://www.cnblogs.com/YungMing/p/4362287.html
Copyright © 2020-2023  润新知