美文网首页
iOS给imageView高效的添加圆角

iOS给imageView高效的添加圆角

作者: Devbrave | 来源:发表于2018-04-19 17:56 被阅读21次
    • 常用的解决方案
    self.view.layer.cornerRadius = 5;
    self.view.layer.masksToBounds = YES;
    

    使用上面的方式会强制Core Animation提前渲染屏幕的离屏绘制, 而离屏绘制就会给性能带来负面影响,会有卡顿的现象出现

    • 使用绘图技术 Core Graphics
    - (UIImage *)circleImage {
        // NO代表透明
        UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
        // 获得上下文
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        // 添加一个圆
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        CGContextAddEllipseInRect(ctx, rect);
        // 裁剪
        CGContextClip(ctx);
        // 将图片画上去
        [self drawInRect:rect];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        // 关闭上下文
        UIGraphicsEndImageContext();
        return image;
    }
    
    • 另外一种实现圆角的方法,其实也是使用绘图技术实现的
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageView.center = CGPointMake(200, 300);
    UIImage *anotherImage = [UIImage imageNamed:@"image"];
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
    [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
                           cornerRadius:50] addClip];
    [anotherImage drawInRect:imageView.bounds];
    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.view addSubview:imageView];
    
    • 使用layermask属性实现
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.coverImageView.bounds cornerRadius:2];
    CAShapeLayer *maskLayer = [CAShapeLayer new];
    maskLayer.frame = self.coverImageView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.coverImageView.layer.mask = maskLayer;
    

    相关文章

      网友评论

          本文标题:iOS给imageView高效的添加圆角

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