iOS 圆角优化

EstelaE22 7年前
   <p>在iOS开发中经常会遇到需要切圆角的需求,最常见的是用户头像。在需要切圆角的图片数量多的情况下,对性能影响非常大。</p>    <p>我们常用的方法是:</p>    <pre>  <code class="language-objectivec">imageView.layer.cornerRadius = aImageView.frame.size.width/2.0;    imageView.layer.masksToBounds = YES;</code></pre>    <p>在这里就不多谈 离屏渲染 了,只要知道,使用上面的代码会发生离屏渲染,频繁发生离屏渲染非常消耗性能。</p>    <h2>优化方案</h2>    <ul>     <li>方法1: 保存视图渲染内容。(略作死)</li>     <li>方法2: 对需要切圆角的图片进行预处理,缓存,显示。</li>     <li>方法3: 覆盖一个圆形镂空图片。</li>    </ul>    <h2>详解</h2>    <p>方法2我觉得不妥,因为每次有新的图片进来都要预处理,把要显示的图片切成圆角,缓存起来。</p>    <p>详细介绍第三种:</p>    <p>在需要显示圆角的图层上覆盖一个镂空的图片,根据颜色,圆角的radius,图片尺寸,这几个参数作为key缓存这张镂空的图片,下次需要覆盖的时候去判断是否已经缓存,复用。</p>    <p>缺点:对视图的背景有要求,单色背景效果就最为理想。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/2b75f81981fa8451b808b91989f6047b.jpg"></p>    <p>注意红色的内容</p>    <p>开发的时候,红色这个地方应该设置为跟背景同一个颜色。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/60e8c20ec22a756eed84a03405eba3c3.jpg"></p>    <p>实际效果</p>    <p>核心代码如下,我把它写层一个UIView的分类,拖进自己的工程里边,import一下就能用了!</p>    <p> </p>    <pre>  <code class="language-objectivec">- (void)addImageWithCornerRadius:(CGFloat)radius color:(UIColor *)color size:(CGSize)size {        // 根据颜色,圆角程度,尺寸 命名文件      NSString *name = [NSString stringWithFormat:@"%@_%f_%@.png", [color colorComponent], radius, NSStringFromCGSize(size)];      NSString *fullPath = [[self pathWithFolder:@"CornerRadius"] stringByAppendingPathComponent:name];        // 判断本地是否已经有缓存了      NSFileManager *fileManager = [NSFileManager defaultManager];      BOOL isExists = [fileManager fileExistsAtPath:fullPath];      UIImage *image;      if (isExists) {          // 从缓存中获取          image = [UIImage imageNamed:fullPath];      } else {          // 缓存中没有 -> 生成图片 -> 保存          image = [self getImageWithSize:size color:color radius:radius];          NSData *data = UIImagePNGRepresentation(image);          [data writeToFile:fullPath atomically:YES];      }      // 将生成的图片覆盖到当前的图层上      UIImageView *imageView = [[UIImageView alloc] initWithImage:image];      imageView.frame = CGRectMake(0, 0, size.width, size.height);      [self addSubview:imageView];  }</code></pre>    <p> </p>    <p>来自:http://www.jianshu.com/p/a88d802820d9</p>    <p> </p>