繁体   English   中英

如何在iOS应用程序中连续更改矩形的高度

[英]How to change the height of rectangle continously in ios app

我有代码将矩形绘制为

- (void)drawRect:(CGRect)frame {
     UIBezierPath* rectanglePath = [UIBezierPath 
     bezierPathWithRect:CGRectMake(67, 50, 2, _height)];
     [UIColor.grayColor setFill];
     [rectanglePath fill];
}

_height值将在单击时连续变化

我有这样的代码

- (void)initialize {
    self.userInteractionEnabled = YES;
    _displayLink = [CADisplayLink displayLinkWithTarget:self 
    selector:@selector(redrawView:)];
    [_displayLink addToRunLoop:[NSRunLoop mainRunLoop]forMode:NSDefaultRunLoopMode];
     NSMutableArray *array = [[NSMutableArray alloc]init];
     [array addObjectsFromArray:@[@“10”,@“20”,@“30”,@“40”]];
 }
 - (void)dealloc {
    [_displayLink invalidate];
    [_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    _displayLink = nil;
 }

 - (void)setInteractionState:(InteractionState)interactionState {
    if (_interactionState == Idle && interactionState != Idle) {
      _displayLink.paused = NO;
    }
    _interactionState = interactionState;
}
- (void)redrawView:(CADisplayLink *)displayLink {
    if (_interactionState == start) {
       _height = [array firstObject];
       [array removeObjectAtIndex:0];
       [array addObject:_height];
     }
}

交互状态如何播放时如何更改高度?

尝试通过Core Animation执行此操作:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(67, 50, 2, _height) cornerRadius:0.0];
shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
shapeLayer.lineWidth = 3.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
[self.view.layer addSublayer:shapeLayer];

UIBezierPath *newPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(67, 50, 2, _height) cornerRadius:0.0];
CABasicAnimation* pathAnim = [CABasicAnimation animationWithKeyPath:@"path"];
pathAnim.fromValue = (id)self.shapeLayer.path;
pathAnim.toValue = (id)newPath.CGPath;
pathAnim.duration = 2.0f;
[self.circle addAnimation:pathAnim forKey:@"redraw"];

self.shapeLayer.path = newPath.CGPath;

UIView类中有两种方法可以重绘视图

  1. - (void)setNeedsDisplay; 重绘整个视图

  2. - (void)setNeedsDisplayInRect:(CGRect)rect; 重画给定区域

例如

- (void)changeHeightTo:(CGFloat)height {
    _height = height;
    [self setNeedsDisplay]; //this method will notify the system
                            //to call `drawRect` in next drawing cycle
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM