如何在UIView上移动手指的同时添加图像?

时间:2012-11-06 04:00:25

标签: objective-c uiview uiimageview touchesbegan touchesmoved

我在将手指移动到屏幕上时在视图中添加图像时遇到问题。

目前它正在多次添加图像,但将它们挤得太紧,并没有真正跟随我的触摸。

编辑:

我想要的是什么:

在拍摄或选择图像后,用户可以从列表中选择另一个图像。我希望用户在视图中触摸并移动他们的手指,所选图像将出现在他们拖动手指的位置,而不会在每个位置重叠。

这有效:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
     UITouch *touch = [touches anyObject];
     currentTouch = [touch locationInView:self.view];

     CGRect myImageRect = CGRectMake(currentTouch.x, currentTouch.y, 80.0f, 80.0f);
     myImage = [[UIImageView alloc] initWithFrame:myImageRect];
     [myImage setImage:[UIImage imageNamed:@"dot.png"]];
     [self.view addSubview:myImage];
     [myImage release];
}

新问题:如何在此处添加空格,以便在视图上绘制图像时不会如此舒适?

3 个答案:

答案 0 :(得分:0)

您可能想要更多地解释您的问题,您到底想要实现什么!如果你不想让图像重叠,你可以试试这个!

UITouch * touch = [touches anyObject];
touchPoint = [touch locationInView:imageView];
prev_touchPoint = [touch previousLocationInView:imageView];

if (ABS(touchPoint.x - prev_touchPoint.x) > 80 
    || ABS(touchPoint.y - prev_touchPoint.y) > 80) {

   _aImageView = [[UIImageView alloc] initWithImage:aImage];
   _aImageView.multipleTouchEnabled = YES;
   _aImageView.userInteractionEnabled = YES;
  [_aImageView setFrame:CGRectMake(touchPoint.x, touchPoint.y, 80.0, 80.0)];
  [imageView addSubview:_aImageView];
  [_aImageView release];
}

答案 1 :(得分:0)

我很抱歉,因为我在公司,我不能发布太大的数据(代码)。压缩是因为您没有检查触摸点与最后一个触摸点的距离。检查点是否在视图中:bool CGRectContainsPoint (CGRect rect,CGPoint point);我的意思是记住touchesBegan:中的触点。如果touchesMomved:中的新触摸大于图像的宽度或左侧,则更新它。并将添加图像视图放在方法中并使用- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg调用它。

答案 2 :(得分:0)

你也可以使用UISwipeGestureRecognizer而不是touchesMoved方法,同时在屏幕上滑动。在viewDidload:方法中,

UISwipeGestureRecognizer *swipeup = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipedone:)];
swipeup.direction = UISwipeGestureRecognizerDirectionUp;
swipeup.numberOfTouchesRequired=1;
[self.view addGestureRecognizer:swipeup];

方法定义:

-(IBAction)swipedone:(UISwipeGestureRecognizer*)recognizer
{
    NSLog(@"swiped");
    UIImageView* _aImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"]];
    _aImageView.frame = CGRectMake(10, 10, 100, 100);
    _aImageView.multipleTouchEnabled = YES;
    _aImageView.userInteractionEnabled = YES;
    CGPoint point = [recognizer locationInView:recognizer.view];
    [_aImageView setFrame:CGRectMake(point.x, point.y, 80.0, 80.0)];
    [self.view addSubview:_aImageView];
    [_aImageView release];
}

目前我正在使用此代码进行向上滑动。我认为它会正常工作。请尝试一下。