如何在椭圆形状视图上平滑移动对象

时间:2015-07-26 17:16:56

标签: objective-c uiview

考虑这张图片

enter image description here

我如何绘制自定义UIView,它实际上只是一个椭圆。我会覆盖drawRect方法吗?有人能告诉我在ecllips路径上拖动红球的代码吗?

1 个答案:

答案 0 :(得分:1)

如果您愿意,可以使用自定义drawRect绘制球,或者您可以使用CAShapeLayer

UIView *ball = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
ball.userInteractionEnabled = TRUE;

CAShapeLayer *ballLayer = [CAShapeLayer layer];
ballLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(50, 50) radius:48 startAngle:0 endAngle:M_PI * 2.0 clockwise:YES].CGPath;
ballLayer.strokeColor = [UIColor blackColor].CGColor;
ballLayer.lineWidth = 0.5;
ballLayer.fillColor = [UIColor redColor].CGColor;
ballLayer.shadowColor = [UIColor blackColor].CGColor;
ballLayer.shadowRadius = 2;
ballLayer.shadowOpacity = 0.75;
ballLayer.shadowOffset = CGSizeZero;
[ball.layer addSublayer:ballLayer];

[self.view addSubview:ball];

创建椭圆可以用类似的方式完成。

拖动球可以用手势完成。

UIGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[ball addGestureRecognizer:pan];

其中:

- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    CGPoint translate = [gesture translationInView:gesture.view];

    if (gesture.state == UIGestureRecognizerStateChanged) {
        gesture.view.transform = CGAffineTransformMakeTranslation(translate.x, translate.y);
    } else if (gesture.state == UIGestureRecognizerStateEnded) {
        gesture.view.center = CGPointMake(gesture.view.center.x + translate.x, gesture.view.center.y + translate.y);
        gesture.view.transform = CGAffineTransformIdentity;
    }
}

你可能想要将球的运动约束到椭圆,然后你只需相应地调整translate坐标。但希望这说明了如何创建手势识别器,并相应地移动UIView