创建圆角视图(四分之一圆)

时间:2014-10-21 09:51:40

标签: ios calayer uibezierpath cgpath cashapelayer

我想创建一个如下所示的视图

enter image description here

为实现这一点,我尝试了以下方法:

UIView *myView = [[UIView alloc] init];
imgView.frame = CGRectMake(50, 150, 200, 200);
[self.view addSubview:imgView];

UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:myView.bounds
                                 byRoundingCorners:UIRectCornerTopRight
                                       cornerRadii:CGSizeMake(50.0, 50.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = myView.bounds;
maskLayer.path = maskPath.CGPath;
myView.layer.mask = maskLayer;

但它对我没用。有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

sudo代码:

    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(50, 150, 200, 200)];
myView.backgroundColor = [UIColor blueColor];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:myView.bounds
                                 byRoundingCorners:UIRectCornerAllCorners
                                       cornerRadii:CGSizeMake(CGRectGetWidth(myView.frame), CGRectGetHeight(myView.frame))];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = myView.bounds;
maskLayer.path = maskPath.CGPath;
myView.layer.mask = maskLayer;


CGRect frame = myView.frame;
CGRect remainder, slice;

CGRectDivide(frame, &slice, &remainder, CGRectGetHeight(frame)/2, CGRectMaxYEdge);

NSLog(@"%@",NSStringFromCGRect(frame));
NSLog(@"%@",NSStringFromCGRect(remainder));
NSLog(@"%@",NSStringFromCGRect(slice));

CGRect remainder2, slice2;
CGRectDivide(remainder, &slice2, &remainder2, CGRectGetWidth(remainder)/2, CGRectMaxXEdge);

NSLog(@"%@",NSStringFromCGRect(remainder));
NSLog(@"%@",NSStringFromCGRect(remainder2));
NSLog(@"%@",NSStringFromCGRect(slice2));

myView.frame = remainder2;
[self.view addSubview:myView];

enter image description here

希望你的回答很清楚..

答案 1 :(得分:0)

它与我一起使用此代码:

UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(50, 150, 200, 200)];
myView.backgroundColor = [UIColor blueColor];
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
[self.view addSubview:imgView];

UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:myView.bounds
                                 byRoundingCorners:UIRectCornerTopRight
                                       cornerRadii:CGSizeMake(50.0, 50.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = myView.bounds;
maskLayer.path = maskPath.CGPath;
myView.layer.mask = maskLayer;

[self.view addSubview:myView];

结果:

enter image description here

答案 2 :(得分:0)

iOS 13,Salah的出色答案得到了Swift 5的翻译

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let standardWidth = max(collectionView.frame.width, collectionView.frame.height)
    return CGSize(width: standardWidth/5, height: standardWidth/5)
}