你可能最好放上盒子和线条 CAShapeLayer s,您可以根据缩放比例更新线宽。
CAShapeLayer
您只需要创建和定义一次线形。但是,对于您的盒子,您需要在更改缩放时重新创建路径(以使盒子的宽度/高度保持恒定的非缩放点大小。
试一试。你应该能够简单地替换你的当前 ZoomingView.m class - 不需要更改视图控制器。
ZoomingView.m
// // ZoomingView.m // // modified by Don Mag // #import "ZoomingView.h" @interface ZoomingView() @property (strong, nonatomic) CAShapeLayer *shapeLayer; @property (strong, nonatomic) CAShapeLayer *boxesLayer; @property (strong, nonatomic) NSArray *points; @end @implementation ZoomingView { CGFloat _zoomScale; CGFloat _kPointSize; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setup]; } return self; } - (void)setup { self.backgroundColor = [UIColor orangeColor]; _points = @[[NSValue valueWithCGPoint:CGPointMake(30, 30)], [NSValue valueWithCGPoint:CGPointMake(200, 40)], [NSValue valueWithCGPoint:CGPointMake(180, 200)], [NSValue valueWithCGPoint:CGPointMake(70, 180)]]; _zoomScale = 1; _kPointSize = 10.0; // create and setup boxes layer _boxesLayer = [CAShapeLayer new]; [self.layer addSublayer:_boxesLayer]; _boxesLayer.strokeColor = [UIColor redColor].CGColor; _boxesLayer.fillColor = [UIColor clearColor].CGColor; _boxesLayer.lineWidth = 1.0; _boxesLayer.frame = self.bounds; // create and setup shape layer _shapeLayer = [CAShapeLayer new]; [self.layer addSublayer:_shapeLayer]; _shapeLayer.strokeColor = [UIColor greenColor].CGColor; _shapeLayer.fillColor = [UIColor clearColor].CGColor; _shapeLayer.lineWidth = 1.0; _shapeLayer.frame = self.bounds; // new path for shape UIBezierPath *thePath = [UIBezierPath new]; for (NSValue *value in _points) { CGPoint point = [value CGPointValue]; if ([value isEqualToValue:_points.firstObject]) { [thePath moveToPoint:point]; } else { [thePath addLineToPoint:point]; } } [thePath closePath]; [_shapeLayer setPath:thePath.CGPath]; // trigger the boxes update [self updateWithZoomScale:_zoomScale]; } - (void)drawRect:(CGRect)rect { // text NSAttributedString *str = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%f", _zoomScale] attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]}]; [str drawAtPoint:CGPointMake(5, 5)]; } - (void)updateWithZoomScale:(CGFloat)zoomScale { _zoomScale = zoomScale; CGFloat scaledPointSize = _kPointSize * (1.0 / zoomScale); // create a path for the boxes // needs to be done here, because the width/height of the boxes // must change with the scale UIBezierPath *thePath = [UIBezierPath new]; for (NSValue *value in _points) { CGPoint point = [value CGPointValue]; CGRect r = CGRectMake(point.x - scaledPointSize / 2.0, point.y - scaledPointSize / 2.0, scaledPointSize, scaledPointSize); [thePath appendPath:[UIBezierPath bezierPathWithRect:r]]; } [_boxesLayer setPath:thePath.CGPath]; _boxesLayer.lineWidth = 1.0 / zoomScale; _shapeLayer.lineWidth = 1.0 / zoomScale; [self setNeedsDisplay]; } @end
结果:
注意: 应该不用多说,但是......这是一个与你合作的起点,而不是“生产代码”。