view 部分设置圆角

1,348 阅读1分钟
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImage *image = [UIImage imageNamed:@"zrx4.jpg"];
    self.imageView = [[UIImageView alloc] initWithImage:image];
    self.imageView.frame = CGRectMake(100, 100, 100, 100);
    [self.view addSubview:self.imageView];

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.imageView.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.imageView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.imageView.layer.mask = maskLayer;
}

@end
关于参数:

第二个参数byRoundingCorners:(UIRectCorner)corners允许指定矩形的部分角为圆角,而其余的角为直角,取值来自枚举:

  typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
    UIRectCornerTopLeft     = 1 << 0,
    UIRectCornerTopRight    = 1 << 1,
    UIRectCornerBottomLeft  = 1 << 2,
    UIRectCornerBottomRight = 1 << 3,
    UIRectCornerAllCorners  = ~0UL
};
其最后一个参数cornerRadii:(CGSize)cornerRadii指定了圆角的半径,但这里需要注意,这个参数的取值是 CGSize类型,也就意味着这里需要给出的是椭圆的半径。