2012-04-10 71 views
1

我想打電話給在ImageView的的imageView.On觸摸的的TouchEvent,我希望得到一個Image.I的像素現在用這樣的: -如何通過在imageView上調用touchEvent來獲取UIimageView中圖像的像素?

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
UITouch *touch = [[event allTouches] anyObject]; 
[sampleImage setBackgroundColor:[UIColor redColor]]; 
//CGPoint location = [touch locationInView:self.view]; 
if ([touch view] == sampleImage) 
{ 

    url1 = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Na.wav", [[NSBundle mainBundle] resourcePath]]]; 
    [sampleImage setBackgroundColor:[UIColor colorWithRed:10.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:1.0]]; 
} 
NSError *error; 
audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:&error]; 
audio.numberOfLoops = 0; 
[audio play]; 
[sampleImage setBackgroundColor:[UIColor redColor]]; 
} 

是否有可能,如果是的話,請幫助? 。 提前致謝。

+1

看到'userInteractionEnabled'財產 – beryllium 2012-04-10 11:03:15

回答

3

您應該添加一個手勢識別您的ImageView,讓委託處理聲音播放給你。

在您的viewDidLoad您實現以下:

UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)]; 
    tap.numberOfTapsRequired = 1; 
    [YourImageView addGestureRecognizer:tap]; 
    [tap release]; 

在你的代碼,你可以把代表和聲音播放,如:

- (void)tapGesture:(UIGestureRecognizer*)sender { 
NSString *path = [[NSBundle mainBundle] pathForResource:@"YourSound" ofType:@"mp3"]; 

    AVAudioPlayer * theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    theAudio.delegate = self; 
    [theAudio play]; 
    [theAudio release]; 
} 

你去那裏!

編輯:


要與touchesMoved上面的選項使用具有如下功能:

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *) event { 
     UITouch *touch = [[event allTouches] anyObject]; 
      CGPoint location = [touch locationInView:self.view]; 
     if ([touch view] == YourImageView) { 
     //play the sound 
     NSString *path = [[NSBundle mainBundle] pathForResource:@"YourSound" ofType:@"mp3"]; 

      AVAudioPlayer * theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
      theAudio.delegate = self; 
      [theAudio play]; 
      [theAudio release]; 

     } 
    } 

你去那裏:)

+0

我可以使用這種方法 - (void)touchesBegan:(NSSet *)觸及事件:(UIEvent *)事件???? – 2012-04-10 11:51:52

+0

是的,我會編輯我的答案。 – BarryK88 2012-04-10 12:23:30

+0

:-Thanks很多:) – 2012-04-10 12:30:37

0

您可以使用UITapGestureRecognizer並可以設置target爲您imageview

enter image description here

+0

我可以用這個方法 - (void)touchesBegan:(NSSet *)觸及事件:(UIEvent *)事件???? – 2012-04-10 11:52:20