在我的应用程序中 - 有四个按钮,名称如下:
在按钮上方有一个 ImageView (或 UIView)。
现在,假设用户点击左上角按钮。上方的图像/ View 应在该特定角处圆角。
我在为 UIView 应用圆角时遇到了一些困难。
现在我正在使用以下代码将圆角应用于每个 View :
// imgVUserImg is a image view on IB.
imgVUserImg.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"any Url Here"];
CALayer *l = [imgVUserImg layer];
[l setMasksToBounds:YES];
[l setCornerRadius:5.0];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor darkGrayColor] CGColor]];
以上代码将圆度应用于提供的 View 的每个角。相反,我只想对选定的角应用圆度,例如 - 顶部/顶部 + 左侧/底部 + 右侧等。
有可能吗?怎么样?
最佳答案
从 iOS 3.2 开始,您可以使用 UIBezierPath
s 的功能来创建开箱即用的圆角矩形(只有您指定的角是圆角的)。然后,您可以将其用作 CAShapeLayer
的路径,并将其用作 View 层的掩码:
// Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds
byRoundingCorners:UIRectCornerTopLeft
cornerRadii:CGSizeMake(10.0, 10.0)];
// Create the shape layer and set its path
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = imageView.bounds;
maskLayer.path = maskPath.CGPath;
// Set the newly created shape layer as the mask for the image view's layer
imageView.layer.mask = maskLayer;
就是这样 - 无需在 Core Graphics 中手动定义形状,也无需在 Photoshop 中创建蒙版图像。该层甚至不需要失效。应用圆角或更改为新角就像定义一个新的 UIBezierPath
并使用它的 CGPath
作为 mask 层的路径一样简单。 bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:
方法的 corners
参数是位掩码,因此可以通过 ORing 对多个角进行圆角运算。
如果您想为此添加阴影,则需要做更多的工作。
因为 "imageView.layer.mask = maskLayer
"应用了 mask ,所以阴影通常不会显示在 mask 之外。诀窍是使用透明 View ,然后将两个子层(CALayer
s)添加到 View 层:shadowLayer
和 roundedLayer
。两者都需要使用 UIBezierPath
。图片作为 roundedLayer
的内容添加。
// Create a transparent view
UIView *theView = [[UIView alloc] initWithFrame:theFrame];
[theView setBackgroundColor:[UIColor clearColor]];
// Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:theView.bounds
byRoundingCorners:UIRectCornerTopLeft
cornerRadii:CGSizeMake(10.0f, 10.0f)];
// Create the shadow layer
CAShapeLayer *shadowLayer = [CAShapeLayer layer];
[shadowLayer setFrame:theView.bounds];
[shadowLayer setMasksToBounds:NO];
[shadowLayer setShadowPath:maskPath.CGPath];
// ...
// Set the shadowColor, shadowOffset, shadowOpacity & shadowRadius as required
// ...
// Create the rounded layer, and mask it using the rounded mask layer
CALayer *roundedLayer = [CALayer layer];
[roundedLayer setFrame:theView.bounds];
[roundedLayer setContents:(id)theImage.CGImage];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
[maskLayer setFrame:theView.bounds];
[maskLayer setPath:maskPath.CGPath];
roundedLayer.mask = maskLayer;
// Add these two layers as sublayers to the view
[theView.layer addSublayer:shadowLayer];
[theView.layer addSublayer:roundedLayer];
https://stackoverflow.com/questions/2264083/