美文网首页
iOS中设置圆角的方式

iOS中设置圆角的方式

作者: aDou小夏 | 来源:发表于2020-06-06 14:31 被阅读0次

    设置圆角的三种方式

    1.设置视图的layer.cornerRadius属性

    UIImageView  *testImageView = [[UIImageView alloc]initWithFrame:CGRectMake(60, 40, 100, 100)];
    testImageView.image = [UIImage imageNamed:@"黄河"];
    testImageView.layer.cornerRadius = 5;
    testImageView.layer.masksToBounds = YES;
    [self.view addSubview: testImageView];
    

    内存消耗16.9
    对uiview或uiimageview使用layer.cornerRadius设置圆角时,会触发离屏渲染,会带来额外的性能消耗,影响UI流畅.
    这种方式适合用在设置圆角比较少页面中,例如,头像的圆角或者按钮的圆角,可以用此方法,对性能的损耗可以忽略不计.
    离屏渲染(Off-Screen Rendering):意为GPU在当前屏幕缓冲区以外新开辟一个缓冲区进行操作;
    在屏渲染(On-Screen Rendering): 意为当前屏幕的渲染, 指的是GPU的渲染操作发生在当前用于显示的屏幕缓冲区中;

    2.贝塞尔曲线+CoreGraphics

    UIImageView  *testImageView = [[UIImageView alloc]initWithFrame:CGRectMake(60, 40, 100, 100)];
    testImageView.image = [UIImage imageNamed:@"黄河"];
    [self.view addSubview: testImageView];
    //开启图片上下文 CGSize size 尺寸, BOOL opaque 透明度, CGFloat scale 比例
    UIGraphicsBeginImageContextWithOptions(testImageView.bounds.size, NO, 0);
    //创建圆角矩形 并剪切 
    [[UIBezierPath bezierPathWithRoundedRect:testImageView.bounds cornerRadius:5] addClip];
    //开始绘制
    [testImageView drawRect:testImageView.bounds];
    testImageView.image = UIGraphicsGetImageFromCurrentImageContext();
    //结束绘制
    UIGraphicsEndImageContext();
    

    内存消耗 8.6
    这种方式适合用在设置圆角的控件比较多的情况下,用UIBezierPath和CoreGraphics框架画出一个圆角.例如使用uitableview或者uicollectionView需要给cell添加圆角/给控件添加圆角,此方式不会操作到layer层,也能够高效的添加圆角.

    3.CoreGraphics

    UIImageView  *testImageView = [[UIImageView alloc]initWithFrame:CGRectMake(60, 40, 100, 100)];
    testImageView.image = [UIImage imageNamed:@"黄河"];
    [self.view addSubview: testImageView];
    //开启图片上下文 CGSize size 尺寸, BOOL opaque 透明度, CGFloat scale 比例
    UIGraphicsBeginImageContextWithOptions(testImageView.bounds.size, NO, 0);
    //获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //设置一个范围
    CGRect rect = CGRectMake(0, 0, testImageView.bounds.size.width/2, testImageView.bounds.size.height/2);
    //给上下文画一个椭圆
    CGContextAddEllipseInRect(ctx, rect);
    //裁剪
    CGContextClip(ctx);
    //开始绘图
    [testImageView drawRect:testImageView.bounds];
    testImageView.image = UIGraphicsGetImageFromCurrentImageContext();
    //结束绘制
    UIGraphicsEndImageContext();
    

    内存消耗 8.6
    CoreGraphics也称为Quartz 2D 是UIKit下的主要绘图系统,频繁的用于绘制自定义视图。Core Graphics是高度集成于UIView和其他UIKit部分的。Core Graphics数据结构和函数可以通过前缀CG来识别。

    相关文章

      网友评论

          本文标题:iOS中设置圆角的方式

          本文链接:https://www.haomeiwen.com/subject/qebgzhtx.html