0

我正在處理圖像編輯應用程序。現在我已經構建了應用程序,用戶可以從他們的圖書館中選擇一張照片或者使用相機拍攝照片。我還有另一個視圖(一個選擇器視圖),用戶可以從中選擇其他圖像。通過選擇其中一個圖像,應用程序將用戶帶回主照片。如何通過觸摸將圖像添加到視圖?

我希望用戶能夠觸摸屏幕上的任何位置並添加他們選擇的圖像。

解決此問題的最佳方法是什麼?

touchesBegan? touchesMoved? UITapGestureRecognizer?

如果有人知道任何示例代碼,或者可以給我一個關於如何處理這個問題的大概想法,那將非常棒!

編輯

現在我能看到的座標,而我的UIImage越來越從我選擇器選擇圖像。但是當我點擊時圖像沒有顯示在屏幕上。有人可以幫助我解決我的代碼,請:

-(void)drawRect:(CGRect)rect 
{  
    CGRect currentRect = CGRectMake(touchPoint.x, touchPoint.y, 30.0, 30.0); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextFillRect(context, currentRect); 
} 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch * touch = [touches anyObject]; 
    touchPoint = [touch locationInView:imageView]; 

    NSLog(@"%f", touchPoint.x); 
    NSLog(@"%f", touchPoint.y); 

    if (touchPoint.x > -1 && touchPoint.y > -1) 
    { 
     stampedImage = _imagePicker.selectedImage; 

     //[stampedImage drawAtPoint:touchPoint]; 

     [_stampedImageView setFrame:CGRectMake(touchPoint.x, touchPoint.y, 30.0, 30.0)]; 

     [_stampedImageView setImage:stampedImage]; 

     [imageView addSubview:_stampedImageView]; 

     NSLog(@"Stamped Image = %@", stampedImage); 

     //[self.view setNeedsDisplay]; 
    } 
} 

對於我NSLogs的例子我看到:

162.500000 
236.000000 
Stamped Image = <UIImage: 0xe68a7d0> 

謝謝!

回答

0

在您的ViewController中,用戶使用方法「 - (void)touchesBegan:(NSSet *)與事件觸發:(UIEvent *)事件」來獲取觸摸發生位置的X和Y座標。下面是說明如何獲取觸摸的X和Y

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    /* Detect touch anywhere */ 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self.view]; 

    NSLog(@"%f", touchPoint.x); // The x coordinate of the touch 
    NSLog(@"%f", touchPoint.y); // The y coordinate of the touch 
} 

一旦你有了這個x和y的數據,您可以設置用戶選擇或使用內置的攝像頭拍攝的圖像,一些示例代碼出現在這些座標處。


編輯:

我認爲這個問題可能在於你如何創造你的UIImage視圖。取而代之的是:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch * touch = [touches anyObject]; 
    touchPoint = [touch locationInView:imageView]; 

    CGRect myImageRect = CGRectMake(touchPoint.x, touchPoint.y, 20.0f, 20.0f); 
    UIImageView * myImage = [[UIImageView alloc] initWithFrame:myImageRect]; 
    [myImage setImage:_stampedImageView.image]; 
    myImage.opaque = YES; 
    [imageView addSubview:myImage]; 
    [myImage release]; 
} 

試試這個:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch * touch = [touches anyObject]; 
    touchPoint = [touch locationInView:imageView]; 

    myImage = [[UIImageView alloc] initWithImage:_stampedImageView.image]; 
    [imageView addSubview:myImage]; 
    [myImage release]; 
} 

如果這不起作用,嘗試檢查如果 「_stampedImageView.image ==無」。如果這是真的,您的UIImage可能沒有正確創建。

+0

我在更徹底地重新閱讀您的問題後更新了我的答案。 – bddicken 2012-07-17 03:59:47

+0

謝謝!我正在處理你的新答案。它幫了大忙! – 2012-07-17 04:54:01

相關問題