如何制作任何视图的圆形

Nir*_*inh 3 iphone user-interface uiview ios

我只想将视图的形状从Square更改为Round.当我尝试使用cornerRadious时,它只是在拐角处.因为我想把整个视图看作圆形.

mat*_*att 6

UIView总是矩形的.但是,您可以使用蒙版使其看起来圆形(或任何形状).为此,请创建一个黑色圆圈的UIImage(在透明背景中).现在获取该UIImage的CGImage并将其作为CALayer的内容.最后,将CALayer设置为mask视图层.

让我们假设您的视图是100 x 100.然后(未测试,但应该非常正确):

UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,100), NO, 0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [UIColor blackColor].CGColor);
CGContextFillEllipseInRect(c, CGRectMake(0,0,100,100));
UIImage* maskim = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CALayer* mask = [CALayer new];
mask.frame = CGRectMake(0,0,100,100);
mask.contents = (id)maskim.CGImage;

view.layer.mask = mask;
Run Code Online (Sandbox Code Playgroud)