我想做的是让用户触摸屏幕,当在该位置检测到触摸时,圆圈的大小将不断增大(并保持增长),直到用户松开为止。

我知道如何检测触摸,但问题是我试图绘制并随着其变大而重新绘制圆圈。

做这个的最好方式是什么?

最佳答案

我将结合使用UILongPressGestureRecognizerNSTimerUIBezierPath来实现此目的。

首先,设置viewDidLoad以添加并配置CAShapeLayer,以容纳要绘制的圆。以下代码最初将在屏幕上绘制一个半径为50点的圆,并向主视图添加长按手势。当然,触摸检测可以按照您想要的任何方式完成。哦,您需要为此导入Quartz。

- (void)viewDidLoad
{
    [super viewDidLoad];

    circleRadius = 50.0f;

    circle = [CAShapeLayer layer];

    [circle setAnchorPoint:CGPointMake(0.5f, 0.5f)];
    [circle setFillColor:[UIColor clearColor].CGColor];
    [circle setStrokeColor:[UIColor colorWithWhite:0.9f alpha:0.7f].CGColor];
    [circle setLineWidth:5.0f];

    [self.view.layer addSublayer:circle];

    [self drawCircleWithRadius:circleRadius];

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressDetected:)];
    [longPress setMinimumPressDuration:0.1];
    [longPress setAllowableMovement:15.0f];
    [self.view addGestureRecognizer:longPress];
}

然后,当识别到长按手势时,检查其状态。如果状态开始,则启动一个重复计时器以调用动画功能。手势结束后,请无效。
- (void)longPressDetected:(UILongPressGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateBegan) {
        timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(animateImageView) userInfo:nil repeats:YES];
    }else if (sender.state == UIGestureRecognizerStateEnded) {
        [timer invalidate];
    }
}

- (void)animateImageView {
    circleRadius += 10.0f;
    [self drawCircleWithRadius:circleRadius];
}

最后,下面的此函数将使用CABasicAnimation将形状图层的path属性动画化为上面指示的值(每次+10)。确保此动画持续时间不大于计时器重复间隔!
- (void)drawCircleWithRadius:(CGFloat)radius {
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    [pathAnimation setFromValue:(id)circle.path];
    [pathAnimation setToValue:(id)[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0f * radius, 2.0f * radius) cornerRadius:radius].CGPath];
    [pathAnimation setDuration:0.1];
    [pathAnimation setRepeatCount:1.0f];
    [pathAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
    circle.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius, CGRectGetMidY(self.view.frame)-radius);
    [circle addAnimation:pathAnimation forKey:@"changePathAnimation"];
}

希望这可以帮助!

关于iphone - 在iPhone中动态重绘调整大小的圆圈,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15249675/

10-13 04:19