0

Xcode 在用户触摸的地方放置一个图像

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch=[[event allTouches]anyObject];
CGPoint point= [touch locationInView:touch.view];

UIImage *image = [[UIImage alloc]initWithContentsOfFile:@"BluePin.png"];
[image drawAtPoint:point];
}

基本上触摸屏图像应该出现在触摸的地方,但什么也没有出现......

4

2 回答 2

1
  1. 你应该像这样初始化一个 UIImage:

    UIImage *image = [UIImage imageNamed:@"BluePin"];
    
  2. 你应该使用一个 UIImageView 来包含一个 UIImage,你不能直接把一个 UIImage 放到 UIView 中。

更新

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch=[[event allTouches]anyObject];
    CGPoint point= [touch locationInView:touch.view];

    UIImage *image = [UIImage imageNamed:@"BluePin"];
    CGRect rect=CGRectMake(point.x, point.y, image.size.width, image.size.height);
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:rect];
    [imageView setImage:image];
    [self.view addSubview:imageView];
}
于 2012-09-12T02:44:53.663 回答
0

要添加到其他答案,请按照以下方式对其进行动画处理:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"Touches began!");
    UITouch *touch= [[event allTouches] anyObject];
    CGPoint point= [touch locationInView:touch.view];

    UIImage *image = [UIImage imageNamed:@"BluePin.png"];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [imageView setFrame: CGRectMake(point.x-(imageView.bounds.size.width/2), point.y-(imageView.bounds.size.width/2), imageView.bounds.size.width, imageView.bounds.size.height)];
    [self addSubview: imageView];
    //self.currentPins += 1;

    [UIView animateWithDuration:2.0 delay:1.0 options:UIViewAnimationOptionCurveLinear  animations:^{
        [imageView setAlpha:0.0];
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        //self.currentPins -= 1;
    }];

   // for(;self.currentPins > 10; currentPins -= 1){
   //     [[[self subviews] objectAtIndex:0] removeFromSuperview];
   // }
}

注释掉的代码是我写的一些额外的代码,用于将屏幕上的引脚数量一次限制为 10 个,假设您有一个名为currentPins的@property 。经过测试,它可以工作,假设我在复制、粘贴和注释掉几行后没有搞砸任何事情。

编辑:忽略注释掉的代码。我实际上混合了两个版本(一个没有动画,一个有)所以它坏了。

于 2012-09-12T03:52:59.760 回答