UIImageView 的圆角效果

本文探讨了iOS中为图片添加圆角的多种方法,包括CALayer、使用placeholder图片、直接裁剪图片等,并重点推荐了一种利用UIBezierPath绘制圆角路径再进行clip的方法,同时提供了避免黑色边框出现且保持高性能的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

iOS 中给图片加圆角的最好方法是什么?

加圆角有很多方法,比如:

  1. 在CALayer中设置cornerRadius属性, 但是很慢, 尤其是图片作为头像显示在UITableView中. 
  2. 用一张头像的placeholder的图, 但是要多读取一张图.
  3. 直接将图片裁剪并加上透明圆角. 但是每张图都要处理.

我认为最好的方法是 

4. drawRect中使用UIBezierPath画一个圆角的path, 然后clip. 但是如果把UIView的opaque设置成YES, 就会出现黑色的边. 不知道有什么办法可以避免这个问题又能得到最高性能.


第一是直接设置参数:

view.layer.shouldRasterize = YES;
view.layer.rasterizationScale = view.window.screen.scale; // or [UIScreen mainScreen]
原文链接:http://stackoverflow.com/questions/11049016/cliptobounds-and-maskstobounds-performance-issue

第二是你说的UIBezierPath的方法,我觉得也挺好的呀:
// Get your image somehow
UIImage *image = [UIImage imageNamed:@"image.jpg"];

// Begin a new image that will be the new image with the rounded corners 
// (here with the size of an UIImageView)
 UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);

 // Add a clip before drawing anything, in the shape of an rounded rect
  [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                        cornerRadius:10.0] addClip];
 // Draw your image
[image drawInRect:imageView.bounds];

 // Get the image, here setting the UIImageView image
  imageView.image = UIGraphicsGetImageFromCurrentImageContext();

 // Lets forget about that we were drawing
  UIGraphicsEndImageContext();

原文链接:http://stackoverflow.com/questions/17593524/using-cornerradius-on-a-uiimageview-in-a-uitableviewcell

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值