- 给UIView设置圆角
UIView * v = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 60, 60)];
v.backgroundColor = [UIColor clearColor];
// v.layer.cornerRadius = 10;
UIGraphicsBeginImageContextWithOptions(v.bounds.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ref, 60, 20);
CGContextAddArcToPoint(ref, 60, 60, 40, 60, 10);
CGContextAddArcToPoint(ref, 0, 60, 0, 40, 10);
CGContextAddArcToPoint(ref, 0, 0, 20, 0, 10);
CGContextAddArcToPoint(ref, 60, 0, 60, 20, 10);
CGContextSetFillColorWithColor(ref, [UIColor purpleColor].CGColor);
CGContextSetStrokeColorWithColor(ref, [UIColor purpleColor].CGColor);
CGContextDrawPath(ref, kCGPathFillStroke);
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView * imv = [[UIImageView alloc] initWithFrame:v.bounds];
imv.image = img;
[v insertSubview:imv atIndex:0];
关于CGContextAddArcToPoint的用法,可以参考
https://my.oschina.net/Kuture/blog/859579
https://blog.csdn.net/Panwave/article/details/45892879
这种方法是绘制出一个image,然后在view上加一层UIImageView。
通常情况下,给UIImageView设置圆角的情况比较多,以下是2种方式
UIImageView * imv = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 90, 40)];
CGSize size = imv.bounds.size;
imv.backgroundColor = [UIColor redColor];
imv.image = [UIImage imageNamed:@"123.png"];
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(20, 20)];
CGContextAddPath(ctx,path.CGPath);
CGContextClip(ctx);
[imv.image drawInRect:rect];
CGContextDrawPath(ctx, kCGPathFillStroke);
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imv.image = newImage;
[self.contentView addSubview:imv];
方法2,这种方法是绘制一个遮罩
UIImageView * imv = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 90, 40)];
imv.backgroundColor = [UIColor redColor];
imv.image = [UIImage imageNamed:@"123.png"];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imv.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerBottomRight | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
maskLayer.frame = imv.bounds;
maskLayer.path = maskPath.CGPath;
imv.layer.mask = maskLayer;
网友评论