使用UIBezierPath的角半径 [英] Corner Radius Using UIBezierPath
问题描述
我正在尝试使用"UIBezierPath"将视图圆角化.我只需要四舍五入topRight和左上角.
I'm Trying to round my view's corners using "UIBezierPath". I Only need to round topRight and Top left.
我已使用以下代码
-(void)setMaskOnView:(UIView *)givenView
{
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:givenView.bounds byRoundingCorners: (UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = givenView.bounds;
maskLayer.path = maskPath.CGPath;
givenView.layer.mask = maskLayer;
}
但是我的右上角不圆.
我用过
UIRectCornerAllCorners
UIRectCornerAllCorners
但这并不能使我圆满结束
But it does not round my right corners
我想念的任何东西吗?
推荐答案
我建议使用其他方法.加载带有圆角的图像,并将其设置为CALayer
的内容.将此层设置为视图层的蒙版.在给定视图的layoutSubivews
或给定视图控制器的viewDidLayoutSubviews
中更新遮罩层的大小.
I suggest different approach. Load image with rounded top corners and set is as contents of CALayer
. Set this layer as mask of your view layer. Update size of your mask layer in layoutSubivews
of a given view or viewDidLayoutSubviews
of given view controller.
将图像作为图层加载进行压缩
CALayer *maskLayer = [[CALayer alloc] init];
UIImage *maskImage = [UIImage imageNamed:@"mask_image.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
maskLayer.contents = (__bridge id _Nullable)(maskImage.CGImage);
mainLayer.mask = maskLayer
在评论中回答您的问题
使用CAShapeLayer或图像作为蒙版,您必须调整蒙版图层的大小,以便它的大小与蒙版图层的大小相同.如果我们在谈论UITableViewCell
,请创建您自己的派生单元格并在layoutSubviews
中更新蒙版形状.下面是示例代码(MyTableCell是从情节提要中加载的):
Either using CAShapeLayer or image as mask you have to resize your mask layer so it will have the same size as masked layer. If we are talking about UITableViewCell
create your own derived cell and update mask shape in layoutSubviews
. Below is example code (MyTableCell is loaded from storyboard):
@interface MyTableCell ()
@property (nonatomic, strong) CAShapeLayer *maskLayer;
@end
@implementation MyTableCell
- (void)awakeFromNib
{
self.maskLayer = [[CAShapeLayer alloc] init];
self.layer.mask = self.maskLayer;
}
- (void)layoutSubviews
{
[super layoutSubviews];
self.maskLayer.path = [self maskPath].CGPath;
}
- (UIBezierPath *)maskPath
{
return [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners: (UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)];
}
@end
这篇关于使用UIBezierPath的角半径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!