如何平移UIView的图表

时间:2012-06-19 06:48:19

标签: ios uiview touch uipangesturerecognizer

实际上,我在MyView中绘制了三角形,矩形,五边形等图,这是UIView的子类。当我触摸MyView上的任何一点(图中是否有该点)时,MyView会被移动。我想触摸图表的内部然后它必须被移动。我在MyView上使用平移手势识别器。请给我建议。

我的代码是:

ViewController.m

- (void)viewDidLoad
{
    MyView *myView = [[MyView  alloc] initWithFrame:CGRectMake(0, 100, 200, 100)];
    [self.view addSubview:myView];
    [super viewDidLoad];
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
    [pinchGesture setDelegate:self];
    [myView addGestureRecognizer:pinchGesture];
    [pinchGesture release];
}

- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer scale]);
        [gestureRecognizer setScale:1];
    }
}

MyView.m

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    context =UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
    // And draw with a blue fill color
    CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1.0);
    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0);

    CGContextMoveToPoint(context, 50.0, 10.0);  
    CGContextAddLineToPoint(context, 5.0, 70.0);  
    CGContextAddLineToPoint(context, 150.0, 55.0); 
    CGContextDrawPath(context, kCGPathFillStroke);
    CGContextClosePath(context);
    CGContextStrokePath(context);

}

1 个答案:

答案 0 :(得分:0)

所以,你有代码在这里做一个捏手势,你想另外做一个平移手势?如果是这样,我建议您在viewDidLoad中创建平移手势:

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(movePiece:)];
[myView addGestureRecognizer:panGesture];
[panGesture release];

然后在您的MyView类中添加一个ivar:

CGPoint _originalCenter;

最后,有了移动视图的方法:

- (void)movePiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan)
    {
        _originalCenter = [gestureRecognizer view].center;
    }
    else if ([gestureRecognizer state] == UIGestureRecognizerStateChanged) 
    {
        CGPoint translation = [gestureRecognizer translationInView:self.view];

        [gestureRecognizer view].center = CGPointMake(_originalCenter.x + translation.x, _originalCenter.y + translation.y);
    }
}

顺便说一句,关于你的代码的一些观察:

  1. 您正在设置捏合手势的代表,但这不是必需的。这是通过initWithTarget方法完成的。

  2. drawRect方法中,我想您在致电CGContextClosePath之前致电CGContextDrawPath

  3. 无论如何,我希望通过向您展示如何使用平移手势来移动子视图来回答这个问题。 (你说“我正在使用泛手势......”但我认为你的意思是“我想使用平移手势......”。)如果我误解了你的问题,那么请澄清并重新解释这个问题,我们可以采取另一个问题克服这个问题。