UIView改变边框宽度中间内容大小不变
最近有个需求是,保证中间圆大小不变,动态改变边线宽度。这里比较简单的方法有两种:view和UIBezierPath
//view
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 100, 100)];
view1.backgroundColor = [UIColor redColor];
view1.layer.cornerRadius = 50;
view1.clipsToBounds = YES;
view1.layer.borderColor = [UIColor greenColor].CGColor;
view1.layer.borderWidth = 10;
[self.view addSubview:view1];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(200, 100, 120, 120)];
view2.backgroundColor = [UIColor redColor];
view2.layer.cornerRadius = 60;
view2.clipsToBounds = YES;
view2.layer.borderColor = [UIColor greenColor].CGColor;
view2.layer.borderWidth = 20;
view2.center = CGPointMake(255, 150);
[self.view addSubview:view2];
//这里保证填充大小不变 view的宽、高的增量和cornerRadius的增量、borderWidth的增量比为:2:1:1
UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(10, 250, 100, 100)];
view3.backgroundColor = [UIColor redColor];
view3.layer.cornerRadius = 50;
view3.clipsToBounds = YES;
[self.view addSubview:view3];
//贝塞尔曲线
UIBezierPath *path=[UIBezierPath bezierPath];
[path addArcWithCenter:CGPointMake(60, 150) radius:50 startAngle:2 endAngle:M_PI*2+2
clockwise:YES];
CAShapeLayer *layer1=[CAShapeLayer layer];
layer1.path=path.CGPath;
layer1.fillColor = [UIColor redColor].CGColor;
layer1.strokeColor = [UIColor greenColor].CGColor;
layer1.lineWidth=10;
[self.view.layer addSublayer:layer1];
UIBezierPath *path1=[UIBezierPath bezierPath];
[path1 addArcWithCenter:CGPointMake(250, 150) radius:55 startAngle:2 endAngle:M_PI*2+2
clockwise:YES];
CAShapeLayer *layer2=[CAShapeLayer layer];
layer2.path=path1.CGPath;
layer2.fillColor = [UIColor redColor].CGColor;
layer2.strokeColor = [UIColor greenColor].CGColor;
layer2.lineWidth=20;
[self.view.layer addSublayer:layer2];
//这里要保证中间填充部分大小不变的情况下,改变lineWidth,lineWidth的增量与radius增量的比例为2:1
UIBezierPath *path2=[UIBezierPath bezierPath];
[path2 addArcWithCenter:CGPointMake(250, 350) radius:50 startAngle:2 endAngle:M_PI*2+2
clockwise:YES];
CAShapeLayer *layer3=[CAShapeLayer layer];
layer3.path=path2.CGPath;
layer3.fillColor = [UIColor redColor].CGColor;
layer3.strokeColor = [UIColor greenColor].CGColor;
layer3.lineWidth=10;
[self.view.layer addSublayer:layer3];
这里需要注意的就是:
对view的操作 borderWidth的大小不影响view的frame。当borderWidth增大时,view的frame不变,那么中间部分的直径就会减小;
对path的操作 lineWidth的大小会影响视图的frame。当lineWidth增大时,view的frame会增大lineWidth,这样只增加lineWidth的大小,中间部分直径不变