图片做圆角是非常常见的,一般用做用户头像什么,ios中怎么实现呢:
1.layer层修改
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"huabianwl003"]];
imageView.center = self.view.center;
[self.view addSubview:imageView];
[imageView.layer setCornerRadius:imageView.frame.size.width/2];
[imageView.layer setMasksToBounds:YES];
这里注意一点,使用了cornerRaius后,shadow投影就无效果了,怎么样能又是圆角又有投影呢,做两层吧!
这个方式是ios开发中最常用的,方便简单,但是开销的性能比较大,尤其在tableView中重用的cell里面使用。具体消耗可以看看这篇文章:http://www.cocoachina.com/ios/20150803/12873.html
2.重绘图片
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImage *image = [UIImage imageNamed:@"huabianwl003"];
image = [self cutImage:image WithRadius:image.size.width/2];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.center = self.view.center;
[self.view addSubview:imageView];
}
//图片剪切
- (UIImage*)cutImage:(UIImage *)orImage WithRadius:(int)radius
{
UIGraphicsBeginImageContext(orImage.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
float x1 = 0.;
float y1 = 0.;
float x2 = x1+orImage.size.width;
float y2 = y1;
float x3 = x2;
float y3 = y1+orImage.size.height;
float x4 = x1;
float y4 = y3;
CGContextMoveToPoint(gc, x1, y1+radius);
CGContextAddArcToPoint(gc, x1, y1, x1+radius, y1, radius);
CGContextAddArcToPoint(gc, x2, y2, x2, y2+radius, radius);
CGContextAddArcToPoint(gc, x3, y3, x3-radius, y3, radius);
CGContextAddArcToPoint(gc, x4, y4, x4, y4-radius, radius);
CGContextClosePath(gc);
CGContextClip(gc);
CGContextTranslateCTM(gc, 0, orImage.size.height);
CGContextScaleCTM(gc, 1, -1);
CGContextDrawImage(gc, CGRectMake(0, 0, orImage.size.width, orImage.size.height), orImage.CGImage);
UIImage *newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimage;
}
重绘图片也是比较耗性能的,具体和第一个方法比怎么样呢,我到是没有比较过,不敢乱说。但是至少可以解决tableView在重用cell时,不断重设layer的问题,因为你可以把重绘好的图片保存在内存中替换掉原来的图片。
3.图片覆盖
怎么说呢,比较low也是比较好的办法,就是在图片上加上一个局部透明的imageView,代码我就不展示了,就是需要UI提供一张中间扣圆的图片。
来源:oschina
链接:https://my.oschina.net/u/1463495/blog/489076