0

实际上,我在 UIView 的子类 MyView 中绘制了三角形、矩形、五边形等图表。当我触摸 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);

}
4

1 回答 1

0

那么,您这里有执行捏合手势的代码,并且您还想执行平移手势?如果是这样,我建议您在 viewDidLoad 中创建平移手势:

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

然后将 ivar 添加到您的 MyView 类:

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

无论如何,我希望我通过向您展示如何使用平移手势来移动子视图的示例来回答这个问题。(您说“我正在使用平移手势……”但我假设您的意思是“我想使用平移手势……”。)如果我误解了您的问题,请澄清并重新表述问题,我们可以再提出一个问题破解它。

于 2012-06-19T14:17:36.503 回答